Types of Inheritance In Java


Types of inheritance:

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

Single Inheritance:

When a class inherits another class, it is known as a single inheritance.

Sample Program:

CLASS A PROGRAM:

package x.ab;
public class A
{
public static void main(String[]args)
{
}
public void methodA()
{
System.out.println(“Base Class Method”);

}
}

CLASS B PROGRAM:

package x.ab;
public class B extends A
{
public static void main(String[]args)
{
B obj = new B();
obj.methodA();
obj.methodB();
}
public void methodB()
{
System.out.println(“Child Class Method”);
}
}

OUTPUT:

  • c:\java>javac -d . A.java
  • c:\java>javac -d . B.java
  • c:\java>java x.ab.B
    Base Class Method
    Child Class Method

Multilevel inheritance:

When a class extends a class, which extends anther class then this is called multilevel inheritance.

Sample Program:

CLASS A PROGRAM:

package x.ab;
public class A
{
public static void main(String[]args)
{
}
public void methodA()
{
System.out.println(“Base Class Method”);

}
}

CLASS B PROGRAM:

package x.ab;
public class B extends A
{
public static void main(String[]args)
{
//B obj = new B();
//obj.methodA();
//obj.methodB();
}
public void methodB()
{
System.out.println(“Child Class Method”);
}
}

Class C PROGRAM:

package x.ab;
public class C extends B
{
public static void main(String[]args)
{
C obj = new C();
obj.methodA();
obj.methodB();
obj.methodC();
}
public void methodC()
{
System.out.println(“New Child Class Method”);
}
}

OUTPUT:

  • c:\java>javac -d . C.java
  • c:\java>java x.ab.C
    Base Class Method
    Child Class Method
    New Child Class Method

Hierarchical Inheritance:

In Hierarchical Inheritance, one class is inherited by many sub classes.

Method Overriding:

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.

Usage of Java Method Overriding:

  • Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.
  • Method overriding is used for runtime polymorphism.

Rules for Java Method Overriding:

  1. The method must have the same name as in the parent class
  2. The method must have the same parameter as in the parent class.
  3. There must be an IS-A relationship (inheritance).

SAMPLE PROGRAM:

package x.ab;
public class C extends B
{
public static void main(String[]args)
{
C obj = new C();
B object = new B();
object.methodB();
object.methodA();
obj.methodB();
obj.methodC();
}
public void methodC()
{
System.out.println(“New Child Class Method”);
}
public void methodB()
{
System.out.println(“FIRST CHILD CLASS METHOD”);
}
}

OUTPUT:

  • c:\java>javac -d . C.java
  • c:\java>java x.ab.C
    Child Class Method
    Base Class Method
    FIRST CHILD CLASS METHOD
    New Child Class Method

Leave a comment

Design a site like this with WordPress.com
Get started