Introduction
Inheritance is a mechanism where one class acquires all the properties and behaviors of another class. The main advantage of Inheritance is reusability; we can use fields and methods of the parent class. We use Inheritance, where an “Is-A” relationship is present between two classes. The parent class in java is denoted as a superclass, whereas the inherited class is denoted as a subclass. We use the keyword extends to inherit the features of the superclass in the subclass.
Types of Inheritance
There are several types of Inheritance:
1] Single Inheritance: In this inheritance, one class acquires the property of another class.
2] Multiple Inheritance: In this inheritance, one class acquires the property of more than one class. Java does not support Multiple Inheritance. In java, multiple inheritance can be obtained with the help of an interface only.
3] Multilevel Inheritance: A chain of inheritance is called multilevel inheritance.
4] Hierarchical Inheritance: When properties of two or more classes are used in a single class.
5] Hybrid Inheritance: A combination of both single and multiple inheritance. Java does not support this type of inheritance.
Advantages of Inheritance
1] Code Reusability
2] Runtime Polymorphism can be achieved with the help of a method overriding concept.
Example of Inheritance
class Employee{
float salary=60000;
}
class Tester extends Employee{
int bonus=9000;
public static void main(String args[]){
Tester p=new Tester();
System.out.println(“Tester salary is:”+p.salary);
System.out.println(“Bonus of Tester is:”+p.bonus);
}
}
Super Keyword:
Super Keyword is used to access the properties (data members or methods) of a superclass or parent class.
The super keyword can be used with variable, method, and constructor.
- super can be used to refer to the variable of parent class where parent class and child class both have the same field.
- super can be used to call the method of parent class when superclass and subclass have a method with the same name. It is mainly used in the case of method overriding.
- super() can be used to call the constructor of the parent class.
Final Keyword:
The final keyword can be used with a variable, a method, or a class in different aspects.
- When we want that a variable value remains constant, the final keyword is used. The value of the final variable can not be changed.
- When we use the final keyword with the method, then it can not be overridden.
- When we use the final keyword with any class, then that class cannot be extended.
One Response