Java inheritance types

Posted in Java Inheritance By Raj On November 26, 2017

 

 

Before reading this, I would recommend you to check my other article on Java Inheritance, in this article, I am going to explain only types of Java inheritance

There are various types of java inheritance

  • Single inheritance
  • Multilevel inheritance
  • Hierarchical inheritance
  • Multiple inheritance ( it is not possible with class )

Java: Single inheritance

When a class is derived from other class then it is called as a single inheritance, check the below diagram the scooter class is extending only from the motorcycle class only, here, the parent class for scooter class is only the motorcycle and the child class for motorcycle is only scooter class

java-single-inheritance

Example: Superclass or parent class

The Motorcycle class which is a superclass for scooter class contains three methods and two fields

Child class

here, the scooter class extending from only motorcycle class and overriding applyBrake method, you can call parent class method’s using super keyword

Output:

Java: Multilevel inheritance

If you see the below example the Motorcycle is derived from the vehicle class and the scooter is derived from the motorcycle class, the parent class for scooter is motorcycle and the parent class for motorcycle is vehicle class

 

java-inheritance-multilevel

In the above example, I have added a new class which is a vehicle class and it contains a new method called changeGear(), you can access this method by creating object for motorcycle class because it extends vehicle class

Can we not access changeGear() method of vehicle class using scooter object, yes you can access this because it extends motorcycle class and the motorcycle class extends vehicle class

Multilevel inheritance example:

Output:

Java: Hierarchical inheritance

In the below example the scooter, standard bike, and sports bike are derived from the motorcycle class, the motorcycle is parent class for all three classes

java-inheritance

Example: Hierarchical inheritance

If you see the below code the sports bike is extended from motorcycle and did not override any method but, the scooter class also extends from the motorcycle and applyBrake method is overridden

Output:

Download code