Inheritance in Java : – Here We inherit the Member of Parent class to the Child class with the intention of reused.
Note: Java doesn’t support hybrid/Multiple inheritance
Example 1
public class A {
int x=10;
}
public class B extends A {
public static void main ( String[] args ) {
B b1 = new B();
System.out.println(b1.x);
}
}
Output : 10
Example 2
public class A {
int x=10;
public void test() {
System.out.println(100);
}
}
public class B extends A {
public static void main ( String[] args ) {
B b1 = new B();
System.out.println(b1.x);
b1.test();
}
}
Output :
10
100
Example 3
Example of Multilevel inheritance
public class A {
public void test1() {
System.out.println(10);
}
}
public class B extends A {
public void test2() {
System.out.println(20);
}
}
public class C extends B {
public void test3() {
System.out.println(30);
}
public static void main ( String[] args ) {
C c1 = new C();
c1.test1();
c1.test2();
c1.test3();
}
}
Output :
10
20
30
Types of Inheritance in Java
- Single Inheritance.
- Multiple Inheritance.
- Multi-Level Inheritance.
- Hierarchical Inheritance.
- Hybrid Inheritance.
Multiple Inheritance in Java
Java Does Not Support Multiple Inheritance at class Level But Multiple Inheritance Can Be Done an Interfaces.