Java Inheritance - Complete Guide
Introduction to Inheritance
Inheritance is a mechanism where a new class (child class) acquires the properties and behaviors (methods) of an existing class (parent class). The main idea behind inheritance is to create new classes that are built upon existing classes.
In Java, inheritance is achieved using the 'extends' keyword. The child class can add new fields and methods, or override the methods of the parent class.
Types of Inheritance
- ✅ Single Inheritance - One class extends another class
- ✅ Multilevel Inheritance - A class extends a class which extends another class
- ✅ Hierarchical Inheritance - Multiple classes extend the same class
- ❌ Multiple Inheritance - Not supported in Java (through classes)
- ✅ Multiple Inheritance through Interfaces - Achieved using interfaces
Inheritance Example
Example
// Parent class
class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating.");
}
public void sleep() {
System.out.println(name + " is sleeping.");
}
}
// Child class inheriting from Animal
class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name); // Call parent constructor
this.breed = breed;
}
// Additional method specific to Dog
public void bark() {
System.out.println(name + " (" + breed + ") is barking: Woof! Woof!");
}
// Overriding parent method
@Override
public void eat() {
System.out.println(name + " the dog is eating dog food.");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog myDog = new Dog("Buddy", "Golden Retriever");
// Methods inherited from Animal
myDog.eat(); // Overridden method
myDog.sleep(); // Inherited method
// Method specific to Dog
myDog.bark();
}
}
Output
Buddy the dog is eating dog food. Buddy is sleeping. Buddy (Golden Retriever) is barking: Woof! Woof!