Inheritance in Java (Single, Multilevel, Hierarchical)
Inheritance in Java: Single, Multilevel & Hierarchical (With Examples)
✨ Quick Summary
In this post, you’ll learn what Inheritance is in Java and how one class can acquire properties and methods of another class. We will cover single inheritance, multilevel inheritance, and hierarchical inheritance with easy examples.
In our previous post, we learned about Encapsulation and how to protect data using getters and setters.
Now it’s time to learn another powerful OOP concept: Inheritance.
1) What is Inheritance?
Inheritance means one class (child class) can acquire the properties and methods of another class (parent class).
Inheritance helps you:
- ✅ Reuse code
- ✅ Reduce duplicate code
- ✅ Create a clean class structure
In Java, we use the keyword extends for inheritance.
2) Example of Single Inheritance
Single inheritance means: one child class inherits from one parent class.
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
public class SingleInheritanceExample {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // from parent class
d.bark(); // from child class
}
}
3) Multilevel Inheritance
Multilevel inheritance means: inheritance in multiple levels.
Example:
- Animal → Dog → Puppy
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
class Puppy extends Dog {
void weep() {
System.out.println("Puppy is weeping");
}
}
public class MultilevelInheritanceExample {
public static void main(String[] args) {
Puppy p = new Puppy();
p.eat(); // from Animal
p.bark(); // from Dog
p.weep(); // from Puppy
}
}
4) Hierarchical Inheritance
Hierarchical inheritance means: multiple child classes inherit from one parent class.
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat is meowing");
}
}
public class HierarchicalInheritanceExample {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
System.out.println("-----");
Cat c = new Cat();
c.eat();
c.meow();
}
}
5) Why Java Does Not Support Multiple Inheritance (With Classes)?
Java does not support multiple inheritance using classes because it can create confusion. This is called the Diamond Problem.
But Java supports multiple inheritance using Interfaces (we will learn later).
Conclusion
Inheritance is a powerful feature in Java that helps you reuse code and build a clean structure.
In the next post, we will learn about Polymorphism in Java with examples!
Very informative
ReplyDeleteGood work.
ReplyDelete