Learn Object-Oriented Programming principles with diagrams and code examples
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of Object-Oriented Programming (OOPs).
extends keyword is used to inherit a class.In single inheritance, a subclass inherits features from a single superclass. It creates a simple 1-to-1 parent-child hierarchy.
// Superclass
class Animal {
void eat() { System.out.println("Eating..."); }
}
// Subclass inheriting from Animal
class Dog extends Animal {
void bark() { System.out.println("Barking..."); }
}
In multilevel inheritance, a class extends another class, which is already extending another class, forming a chain of inheritance.
class Animal {
void eat() { System.out.println("Eating..."); }
}
class Dog extends Animal {
void bark() { System.out.println("Barking..."); }
}
// Inherits properties from both Dog and Animal
class BabyDog extends Dog {
void weep() { System.out.println("Weeping..."); }
}
In hierarchical inheritance, multiple subclasses inherit from a single superclass.
class Animal {
void eat() { System.out.println("Eating..."); }
}
class Dog extends Animal {
void bark() { System.out.println("Barking..."); }
}
class Cat extends Animal {
void meow() { System.out.println("Meowing..."); }
}
Multiple inheritance occurs when a subclass extends more than one parent class. Java does not support this using classes to avoid ambiguity (the "Diamond Problem"), but supports it via Interfaces.
interface Printable {
void print();
}
interface Showable {
void show();
}
// Implementing multiple interfaces using the 'implements' keyword
class Document implements Printable, Showable {
public void print() { System.out.println("Printing..."); }
public void show() { System.out.println("Showing..."); }
}
Hybrid inheritance is a combination of two or more types of inheritance. Since it involves multiple inheritance, it is only achieved through Interfaces in Java.
class Grandparent {}
interface Parent1 {}
interface Parent2 {}
// Combining Single + Multiple Inheritance
class Child extends Grandparent implements Parent1, Parent2 {
// Implementation
}