Inheritance in Java

May 12, 2017

Inheritance allows code defined in one class to be reused in another class. Inheritance represents IS-A relationship or parent-child relationship.

Inheritance in Java allows an object to acquire all the properties (variables) and behavior (methods) of the parent object.

In Java to inherit a class, extends keyword is used.

The class which inherits from other class is known as Superclass or Base class or Derived class or extended class, and the class which inherits this Super class is known as Child Class or Subclass.

Superclass does n’t know anything about the child which inherits it, but the subclasses which inherit the superclass must explicitly declare the inheritance relationship.

The idea behind Inheritance:

The idea of inheritance is simple but powerful: When you want to create a new class, and there is already a class that includes some of the code that you want, you can derive your new class from the existing class.

This way you can reuse the variables and methods of the existing class without having to write (and debug!) them yourself.

An Example of Inheritance:

Let us consider, a class with name Machine which has a variable with name engine and three methods with name start(), stop() and setEngine().

Another class is created with name Car which inherits(extends) Machine class. Here, we created a method with name restart() and accessed the variable (with name engine) of the super class.

Another class is created which has a main method, here we have created three different objects, see below code for your reference:

In above code, we have created three different objects with name “mac”, “alto” and “bmw”.

“mac” object is an instance of class Machine, so can access methods and variables only from Machine class.

“alto” is an instance of Car class, and can access methods and variable of both the classes (Machine and Car).

“bmw” is an instance of Machine class, but is initialized as  Car class, so can access method of only Machine class, but the constructor of both the classes are called.

Note: Constructors are not inherited by subclasses, but the constructor of a superclass can be invoked from a subclass.

Things you can do in a subclass:

  • The inherited members (variables and methods) of a superclass can be used directly in the subclass.
  • You can declare a variable in the subclass with the same name as in superclass (hiding the variable of super class) not recommended.
  • You can write a method with same name and signature as one in the superclass (Overriding).
  • You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using super keyword.

PS: For any questions, queries or feedback. Feel free to write us at saurabh@qatechhub.com or support@qatechhub.com

Saurabh

About the Author

Saurabh

Follow Saurabh:

Leave a Comment: