Inheritance in Java

Sarwan Dahri
Nov 5 · 3 min read

Inheritance is just like a Father and a Son, it’s like a Son acquire properties of father and some properties of its own, but in real world it does not sound like that but in programming in java or any other language it sounds like it. There is a parent class and a child class which acquire the properties of the parent class. Class have properties like methods/instance variables etc.

Why we use inheritance?

For Code Reusability: We use inheritance so we can use code as many times as we can and we don’t have to write same code every time for every task we perform.

For Efficiency: Inheritance increases the speed of Program.

For acquiring Encapsulation: If we have some common attributes, then we encapsulate these in a parent class and just give specific attributes to child classes.

For acquiring Polymorphism: We can also use Polymorphism with Inheritance in Java. So that based on the type of Child class, same class behaves differently.

Keywords to Note:

extends and implements

extends is a keyword for inheriting the properties of a class. A class which is extended by another class is called parent class and a class which extends the class is called a child class.

implements is a keyword for inheriting the properties of a interface. Like class a interface can also be extended a class but keyword for this is “implements” by this keyword a class can implement a interface.

Example Code

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

looking on following diagram it is easy to understand the types

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Hierarchical Inheritance

For Your information:

There are more types but we are talking about inheritance in java these types are not supported by java but for your information we discussed it following.

4. Multiple inheritance (not Supported by java)

5. Hybrid inheritance (not supported by java)

Example codes of types of inheritance in java

1.Single Inheritance

2.Multilevel Inheritance

3.Hierarchical Inheritance

    Sarwan Dahri

    Written by

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade