Types of INHERITANCE CONCEPTS IN JAVA

 Types of Inheritance in Java

​Java only supports Single Inheritance through classes, meaning a class can only inherit from one direct parent class. However, it can achieve effects similar to other types through interfaces.

​Single Inheritance: A class inherits from only one superclass.

​Example: Class B extends Class A

​Multilevel Inheritance: A class inherits from a parent, and that parent also inherits from another class.

​Example: Class C extends Class B, and Class B extends Class A

​Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.

​Example: Class B extends Class A, and Class C extends Class A

​🛑 Note: Multiple Inheritance (inheriting from two or more classes) is not supported in Java classes to avoid the "Diamond Problem." This concept is supported through Interfaces.

​Key Mechanisms Related to Inheritance

​1. super Keyword

​The super keyword is used inside a subclass to refer to the immediate superclass's members.

​Accessing a Superclass Field: super.fieldName

​Calling a Superclass Method: super.methodName()

​Calling a Superclass Constructor: super(arguments)

​This must be the first statement in the subclass constructor.

​2. Method Overriding

​This is the ability of a subclass to provide a specific implementation for a method that is already provided by its superclass.

​The method signature (name and parameter list) must be the same.

​The return type must be the same or a covariant return type (a subclass of the superclass's return type).

​The access modifier cannot be more restrictive than the superclass method.

​3. final Keyword

​The final keyword can be used to restrict inheritance:

​final class: A class declared as final cannot be inherited.

​final method: A method declared as final cannot be overridden in a subclass.

Comments