In Java, Inheritance allows one class to acquire the properties and methods of
another class using the extends keyword.
Java supports the following types of inheritance (except Multiple Inheritance
through classes, which is achieved using interfaces):
1. Single Inheritance
One class inherits from another class.
Example
class Parent {
void display() {
System.out.println("This is the Parent class");
}
}
class Child extends Parent {
void show() {
System.out.println("This is the Child class");
}
}
public class SingleInheritanceExample {
public static void main(String[] args) {
Child obj = new Child();
obj.display(); // From Parent
obj.show(); // From Child
}
}
2. Multilevel Inheritance
A class inherits from another class, which itself inherits from another class.
Example
class GrandParent {
void message1() {
System.out.println("GrandParent class");
}
}
class Parent extends GrandParent {
void message2() {
System.out.println("Parent class");
}
}
class Child extends Parent {
void message3() {
System.out.println("Child class");
}
}
public class MultilevelInheritanceExample {
public static void main(String[] args) {
Child obj = new Child();
obj.message1();
obj.message2();
obj.message3();
}
}
3. Hierarchical Inheritance
Multiple classes inherit from the same parent class.
Example
class Parent {
void display() {
System.out.println("Parent class");
}
}
class Child1 extends Parent {
void show1() {
System.out.println("Child1 class");
}
}
class Child2 extends Parent {
void show2() {
System.out.println("Child2 class");
}
}
public class HierarchicalInheritanceExample {
public static void main(String[] args) {
Child1 obj1 = new Child1();
obj1.display();
obj1.show1();
Child2 obj2 = new Child2();
obj2.display();
obj2.show2();
}
}
4. Multiple Inheritance (Through Interfaces)
Java does NOT support multiple inheritance with classes to avoid ambiguity, but it
can be achieved using interfaces.
Example
interface A {
void methodA();
}
interface B {
void methodB();
}
class C implements A, B {
public void methodA() {
System.out.println("Method from Interface A");
}
public void methodB() {
System.out.println("Method from Interface B");
}
}
public class MultipleInheritanceExample {
public static void main(String[] args) {
C obj = new C();
obj.methodA();
obj.methodB();
}
}