Inheritance in Java

In this tutorial, we will learn about Inheritance in Java.

Different kinds of objects often have certain things common with each other. Let’s take an example of Car. A car can be of Sports car, Luxury Car or a normal Sedan Car. All these are cars having certain things in common such as seats, steering wheel, doors etc. Each car might have some extra features. For ex. Sports car can have dual-stage airbags, fog lamps. A Luxury car can have child seat anchor points, ride height adjustment.
So the common features can be defined in one class and the other classes can extend this class to have these features with some extra features. In Java this is called as Inheritance.

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of another object.
It is one of the important OOP’s concepts. Using inheritance we can create a hierarchy between classes by inheriting from other classes. When you inherit from other class, you can reuse methods and variables of parent class.

A class which is inherited is known as Parent class and the class which is inheriting the parent class is known as Subclass.

In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses. Inheritance represents IS-A relationship.

Inheritance in Java can be achieved using an extends keyword.

Example of Inheritance:

Car.java:

Let’s create a Car.java class.

Now create subclasses extending Car.java class.

SportsCar.java:

LuxuryCar.java:

Let’s create InheritanceDemo.java class.

InheritanceDemo.java:

Now run the demo class to check the output.

Output:

If you observe the output, the Name and Price fields are not available in SportsCar.java and LuxuryCar.java but still the values for these fields have been accessible in subclass. This indicates that the fields in Superclass are inherited in subclasses.

Key points about Inheritance:

1) The important point to note about Inheritance is that, Java doesn’t support multiple inheritance.
2) One of the main advantage of Inheritance is code reuse as subclasses inherit the attributes and behaviors of super class.
3) Superclass Constructors are not inherited by subclass.
4) You cannot access Private members of Superclass directly but you can access them indirectly using setter and getter methods.
5) You can’t extend Final Classes in java.
6) Super class methods and variables can be accessed from subclass using super keyword.

Other Tutorials:

 

Related posts

Leave a Comment