Types of inheritance in Java — common interview question
Please explain types of inheritance in Java
It is a popular question in the interview for the Software Engineer or SDET positions.
In Java, inheritance is a mechanism that allows one class to inherit the fields and methods of another class. The class that inherits the properties of another class is called a subclass (or derived class, or child class), and the class whose properties are inherited is called a superclass (or base class, or parent class).
Java supports the following types of inheritance:
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Multiple Inheritance (Through Interfaces)
Single Inheritance
In a single inheritance, a class can inherit from only one superclass. Java primarily supports single inheritance to avoid complications and simplification of the design. This means each class can extend only one other class.
class A { }
class B extends A { } // B inherits from A
Multilevel Inheritance
In multilevel inheritance, a class can inherit from a derived class, making this class a base class for another class. It creates a chain of inheritance.
class A { }
class B extends A { } // B inherits from A
class C extends B { } // C…