Inheritance in Java.

Inheritance in Java.

Isaac Tonyloi

Photo by Vlad Tchompalov on Unsplash

Inheritance is one of the key features of Object Oriented Programming that allows a class to inherit methods and features from another class.

A class that inherits from another class is known as the child class or the sub class. On the other hand the class whose properties and methods are inherited is known as the parent class or the super class.

One of the key features of inheritance is that it allows reusability of code i.e inheritance allows programmers to reuse methods and attributes from already existing classes to create new classes.

In Java to inherit from a class we use the keyword extends. The keyword indicates that the current class is inheriting attributes and methods from another class.

There are three types of inheritance in java: single, multi-level, hierarchical and hybrid.

  1. Single Inheritance.

It is one of the simplest forms of inheritance in Java, therefore it is easy to understand. In this type of inheritance a class only inherits from one parent or base class.

Output

2.MultiLevel Inheritance.

This is an Object Oriented mechanism that allows programmers to create new classes by inheriting attributes and methods from derived/ subclasses. Under this type of inheritance new classes are created from a class that in turn inherits from a different class thus the term multilevel inheritance.

OutPut.

3.Hierarchical Inheritance.

Image by Author

In this type of inheritance several classes in a java program inherit properties and methods from a single base class. For instance if we have class C and another class B inheriting from a single class A this form of inheritance is known as hierarchical inheritance.

Output.

4.Multiple inheritance.

Image by author

This type of inheritance cannot be implemented in java using classes, however it can be implemented using interfaces. Multiple inheritance as the name suggests is a type of inheritance where a class can inherit attributes and methods from several superclasses.

The main reason why java does not support multiple inheritance is to avoid complexity and ambiguity when writing programs that have several classes and methods.

Output.

5.Hybrid Inheritance.

Image by author

Hybrid inheritance is a combination of two or more of the following types of inheritances: (single inheritance, multilevel inheritance and hierarchical inheritance). However when using multiple inheritance to implement hybrid inheritance , we have to use interfaces since Java does not support multiple inheritance using classes.

Output.

Connect with me: www.linkedin.com/in/isaactonyloi