Inheritance
Inheritance
INTRODUCTION
• Inheritance is a strategy or a process of acquiring the properties from one class to another class.
Here, properties are nothing but variables and methods of a class.
• A class can only inherit the fields and methods of another class, if it extends the class. For example, in the
following snippet, class A extends class B. Now class A can access the fields and methods of class B.
class A extends B
}
INTRODUCTION
• Child Class: The class that extends the features of another class is known as child class, sub class or derived
class. In the above code, class A is the child class.
• Parent Class: The class that shares the fields and methods with the child class is known as parent class, super
class or Base class. In the above code, Class B is the parent class.
TERMINOLOGIES USED IN INHERITANCE:
• instanceof keyword returns true, if an object belongs to the class or its parent class.
1. Single Inheritance
In Single inheritance, a single child class inherits the properties and methods of a single parent class. In the following diagram:
class B is a child class and class A is a parent class.
2. Multilevel Inheritance
In multilevel inheritance, a parent class becomes the child class of another class. In the following diagram: class B is a parent class
of C, however it is also a child class of A. In this type of inheritance, there is a concept of intermediate class, here class B is an
intermediate class.
3. Hierarchical Inheritance
In hierarchical inheritance, more than one class extends the same class. As shown in the following diagram, classes B, C & D
extends the same class A.
4. Hybrid Inheritance
Hybrid inheritance: Combination of more than one types of inheritance in a single program. For example, class B & C extends A and
another class D extends class C then this is a hybrid inheritance example because it is a combination of single and hierarchical
inheritance.
MULTIPLE INHERITANCE
It refers to the concept of one class extending more than one classes, which
means a child class has more than one parent classes. For example class C
extends both classes A and B. Java doesn’t support multiple inheritance.
INHERITANCE ACCESS SPECIFIER IN JAVA
• The derived class can inherit only those data members and methods of parent class, that are
declared as public or protected.
• If the members or methods of super class are declared as private then the derived class cannot
access them. The private members can be accessed only in its own class. Such private
members can only be accessed using public or protected getter and setter methods of super
class
INHERITANCE AND METHOD OVERRIDING
When we declare the same method in child class, which is already present in the parent class
then this is called method overriding. In such case, when we call the method from child class
object, the child class version of the method is called. However, we can call the parent class
method using super keyword then it calls the parent class method