Inheritance is used to store information and manage the information in a hierarchical order. It is the process of defining a new class based on an existing class where a child class acquires the properties of the parent class. The subclass (Child/Derived class) inherits the properties of the ParentClass, and the class from which the properties are inherited is called a Super Class (Parent class or Base class).
Inheritance allows us to reuse of code and improve the reusability in Java application so that a class has to write only the unique features and rest of the common properties and functionality can be extended by the other class.
Super Class- Superclass is a class whose properties and behaviour are used by the child class.
Sub Class- Subclass is a class that inherits the properties of another class.
Reusability- Inheritance allows the reuse of code. When we create a new class and there is already a class that includes some common properties or feature that a class has to write. It can be driven to the new class from the existing class by reusing the field and method.
Extend keywords are used to inherit the properties of the class.
In the following example, we are demonstrating Java inheritance. In this example, you can observe
When an object to Bike, Car, and Truck class is created, a copy of the contents of the superclass (Vehicle) is made within it. That is why using the object of the subclass you can access the members of a superclass.
The Superclass is a reference variable used to hold the subclass object. Reference variable allows you access only the members of the superclass, for accessing the members of subclasses it is recommended to always create a reference variable to the subclass. In this scenario, you may notice that each child has exactly one parent this is known as single inheritance. Single inheritance doesn’t prevent parents from having multiple children.
Note: The advantage of Inheritance is that the code that already exists code in a superclass can be reused in sub/derived class.
Contributed by: Poonam Tomar