Types of Inheritance

 Inheritance in Java
 

Java Inheritance is a fundamental concept in Object-Oriented Programming. It is the mechanism in Java by which one class is allowed to inherit the features (fields and methods) of another class – creating new classes based on existing ones. A class that inherits from another class can reuse the methods and fields of that class.

Keywords:

    •    Super Class / Parent Class: The class whose features are inherited is known as a superclass (or a base class or a parent class).
    •     Sub Class / Child Class: The class that inherits from the parent class is known as a subclass (or a derived class, extended class or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
    •       extends: The keyword is used to inherit properties from a superclass.

 

Syntax

class <sub_class_name> extends <super_class_name>

{

         // Additional fields and methods

}

 

Need for Inheritance

Inheritance is required in Java to reuse code efficiently, build hierarchical structures, and allow objects to share and extend behavior. It provides a structured way to avoid duplication and improve maintainability.

1.   Code Reusability

2.   Avoid Code Duplication

3.   Method Overriding (Polymorphism) – Change existing features

4.   Extensibility — Easier to Add New Features

5.   Improves Maintainability and Scalability


Types of Inheritance

1.   Simple Inheritance – A sub-class is derived from only one super class. It inherits the properties and behavior of a single-parent class. 

(Super class / parent class)

(Sub class / child class)

2. Multilevel Inheritance - Multilevel Inheritance has one superclass and one subclass and one or more intermediate classes. The intermediate class is both a subclass and superclass – It inherits from the parent class and acts as a parent class to another sub class.

(Super class / Parent class)

 

(Intermediate class. B is a sub class of A and super class of C)

 

(Sub class / Child class)

3. Hierarchical Inheritance - More than one subclass is inherited from a single base class. i.e. more than one derived class is created from a single base class.

 

A – Super class / Parent class

 

 

 

 

B and C – Sub class / Child class

4. Hybrid Inheritance – A mix of two or more types of Inheritance.

 

§  B inherits from A – Simple inheritance

 

§  B and C inherits from A – Hierarchical inheritance

 

§  C inherits from A, D inherits from C – Multilevel inheritance  

 


No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu