Last Updated:

Inheritance in Java. Simple and with examples

Inheritance in Java is a transitional one, so if a Sedan extends the Car class, it means that the Sedan is also inherited from the Vehicle class. Thus, the Vehicle becomes a superclass for both the Car class and the Sedan class.

Inheritance is widely used in Java applications. A good example would be the Exception class, which is inherited by other classes to create more specific error classes.

In Java, each class implicitly extends the java.lang.Object class, so the Object class is at the top level of the inheritance hierarchy in Java.

A simple example of implementing inheritance in Java:

Animal.java

The Animal class is the base class here. Now let's create a Cat class that will inherit from Animal.

Cat.java

The extends keyword is used in Java to implement inheritance.

Now let's write a simple test class to test some of the methods of the Cat class.

AnimalInheritanceTest.java

The result of the program:

It is clear from the results of the program execution that the Cat class does not have a getEats() method, but it still works because it inherits from the Animal class.

Important Inheritance Considerations in Java

  • The private members of the superclass are not available to subclasses. As in our example, the variable class Animal noOfLegs is not available for the Cat class. However, this problem is solved by creating the getter and setter methods.
  • A subclass with a default access level is available to other subclasses only if they are in the same package! Read more about access modifiers in Java here.
  • Superclass constructors are not inherited by subclasses.
  • If a superclass does not have a default constructor, the subclass must have an explicit constructor. Otherwise, it will throw a compile time exception.
  • Java does not support multiple inheritance, so a subclass can inherit only one class!