Sitemap
Raj R. Sharma

Raj R. Sharma

Passionate Computer Engineering Student exploring the world of software. LinkedIn: https://www.linkedin.com/in/raj-r-sharma/

Inheritance in Java.

2 min readSep 21, 2024

Inheritance is an important topic of object oriented programming. When we want to inherit properties and methods (which are not private) of a class to a another class then it is called as Inheritance.

Suppose we have a class Vehicle which have some properties such as speed, fuel type, etc. and methods like breaking(), accelerating(), etc., now we required to make another class Car having all methods and properties of Vehicle with some additional properties. In this case we can inherit Vehicle class while creating Car class, this will allow objects of Car class to access public methods and properties of vehicle class.

The class which is inherited to other class(like Vehicle class in above example) is called as Parent, Super or base class.

On the other hand the class which inherits properties and methods of other class is called a Child, Sub or Derived class.

Consider following example:

//Test.java
class Vehicle{
private String fuel;

public Vehicle()
{
fuel = "Petrol";
System.out.println("Inside vehicle constructor!!");
}

public String getfuel(){
return this.fuel;
}
}

class Car extends Vehicle {
public Car()
{
System.out.println("Inside Car constructor!!");

}
}

class Test{
public static void main(String args[])
{
Car myCar = new Car();
System.out.println(myCar.getfuel());
}
}
/*
Output:
Inside vehicle constructor!!
Inside Car constructor!!
Petrol
*/

Above example shows single inheritance. In this example Car is child/sub/derived class and Vehicle is a parent/super/base class.

Get Raj R. Sharma’s stories in your inbox

Join Medium for free to get updates from this writer.

There are various types of inheritance:

  1. Single Inheritance: In such type of inheritance there are only two classes involved i.e. parent class and child class.
Single Inheritance

2. Multilevel inheritance: Suppose a class B inherits class A and another class C inherits class B. Such type of inheritance is called Multilevel inheritance.

Multilevel Inheritance

3. Multiple inheritance : In such kind of inheritance a single child class inherits two or more parent classes. Multiple inheritance of class is not supported by Java.

These where some important types of inheritance in Java. We also have other types like hierarchical inheritance, hybrid inheritance.

In this article we have seen different types of inheritance. There is much more to explore in Java.

Keep Coding…

--

--

Raj R. Sharma
Raj R. Sharma

Written by Raj R. Sharma

Passionate Computer Engineering Student exploring the world of software. LinkedIn: https://www.linkedin.com/in/raj-r-sharma/