Inheritance
Inheritance is a fundamental concept in Java's object-oriented programming (OOP) paradigm. It allows you to create a new class based on an existing class, inheriting the attributes and methods of the parent class. The class that is inherited from is called the "superclass" or "base class," and the class that inherits from it is called the "subclass" or "derived class."
Inheritance in Java can take several forms, each serving specific purposes. The common types of inheritance are:
1. Single Inheritance
A class can inherit from only one other class.
For example, the Car
class can inherit from the Vehicle
class.
2. Multilevel Inheritance
In multilevel inheritance, a class can inherit from another class that is itself inherited from another class.
For example, the SportsCar
class can inherit from the Car
class, which inherits from the Vehicle
class.
3. Hierarchical inheritance
In hierarchical inheritance, there is a single superclass from which multiple subclasses inherit.
For example, the Animal
class can be inherited by the Dog
, Cat
, Bird
, and Fish
classes.
4. Multiple Inheritance
Java does not support Multiple Inheritance through classes. But with the introduction of default methods in Java 8, interfaces can have method implementations. it allows a class to implement multiple interfaces, achieving a form of multiple inheritance through interfaces.
For example, class Bird is inheriting classes Flyer and Swimmer
5. Hybrid Inheritance (NOT SUPPORTED IN JAVA)
Hybrid inheritance combines multiple forms of inheritance in a single program.
Java does not support hybrid inheritance involving both class and interface inheritance due to the "diamond problem." It can lead to ambiguity in method resolution.
Diamond Problem
The diamond problem in Java is a situation that arises when a class inherits from two classes that have a common superclass. This can lead to ambiguity, as the subclass inherits two copies of the same method from its parent classes.
The D
class inherits the doSomething()
method from both the B
class and the C
class. This creates an ambiguity, as the compiler does not know which version of the doSomething()
method to call.
The use of interfaces is the preferred way to resolve the diamond problem in Java. This is because it allows us to avoid the ambiguity of multiple inheritance, and it also makes our code more modular and reusable.
Last updated