Type of inheritence
Type of inheritence
Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. In the image below, class A serves as a
base class for the derived class B.
// Java program to illustrate the
// concept of single inheritance
import java.io.*;
import java.lang.*;
import java.util.*;
class one {
public void print_geek()
{
System.out.println("Geeks");
}
}
class two extends one {
public void print_for() { System.out.println("for"); }
}
// Driver class
public class Main {
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also acts as the base
class for other classes. In the below image, class A serves as a base class for the derived class B, which in turn serves as a base
class for the derived class C. In Java, a class cannot directly access the grandparent’s members
// Java program to illustrate the
// concept of Multilevel inheritance
import java.io.*;
import java.lang.*;
import java.util.*;
class one {
public void print_geek()
{
System.out.println("Geeks");
}
}
class two extends one {
public void print_for() { System.out.println("for"); }
}
class A {
class B extends A {
class C extends A {
class D extends A {
}
// Driver Class
obj_B.print_A();
obj_B.print_B();
obj_C.print_A();
obj_C.print_C();
obj_D.print_A();
obj_D.print_D();
}
4. Multiple Inheritance (Through Interfaces)
In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Please note
that Java does not support multiple inheritances with classes. In java, we can achieve multiple inheritances only through
Interfaces. In the image below, Class C is derived from interfaces A and B.
// Java program to illustrate the
// concept of Multiple inheritance
import java.io.*;
import java.lang.*;
import java.util.*;
interface one {
public void print_geek();
}
interface two {
public void print_for();
}