An overview of Inheritance In Java:
Inheritance in Java means one class legally acquires properties from another class. Inheritance allows the reuse of a particular class, also known as a superclass, to create a new class or subclass. The new class can acquire the properties of the superclass. To understand the concept of inheritance, we can correlate it with real-life examples. For instance, the animal class contains a subclass of vertebrates and invertebrates. They are further classified into mammals, reptiles, fish, etc. However, all these animals contain certain attributes that are common to the animal kingdom.UML Notation for Inheritance in java:
- A extends B
- While the class ‘A’ shares the properties,
- Class ‘B’ inherits or acquires the properties.
- The keyword “extends” is the term between these two classes.
What is a Super Class in Java?
The class that shares its properties (in this case, A class) is known as a base class, parent class, or superclass.
What is a Sub Class in Java?
The class that acquires the properties from another class is the child, acquired, or derived class.
- This is how the concept of inheritance is depicted in Java.
- Moreover, B acquires the properties of A.
- However, class A cannot acquire or access the properties of B.
How to write a program for inheritance in Java?
class A{}
class B extends A
{
public static void main (string [] args);
{
}
}
Object Creation from Simple Inheritance in Java:
In simple inheritance, there are four possibilities for creating an object.
For example,
1) Super Class Objects:
A a = new A(); Superclass Object
2) Sub-Class Objects:
(Assignment Operators) Superclass reference holds the sub-class object—right hand held by left hand.
B b = new B(); Subclass Object
3) Superclass reference holds subclass object.
A a1 = new B();4) B b1 = new A()
The fourth condition is not possible.
Theoretically, though we write such kinds of statements practically, it is not possible because subclass references cannot hold superclass references.
Notably, a superclass can hold a subclass but cannot access the sub-class properties.
On the other hand, a subclass cannot hold objects of a superclass but can access superclass properties.
Inheritance in Java: an Example program
What are the different Inheritance Types in Java?
There are five methods of inheritance in Java. They include,
Simple Inheritance:
A single subclass inherits from a single superclass.
Multiple Inheritance:
A subclass inheriting from more than one superclass. (Java doesn’t support)
Multilevel Inheritance:
A subclass inherits from consecutive super classes.
Hierarchical Inheritance:
A single superclass contains multiple subclasses. Again, these subclasses can have their own subclasses.
Hybrid Inheritance:
The Combination of hierarchical and multiple inheritance constitutes hybrid inheritance.