Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object.
• It is an important feature of OOPs.
• Inherited class is called as parent class or super class or base class
• Class that inherits a parent class is called as child class or sub class or derived class
• ‘extends’ keyword is used to inherit a class
• Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Method Overriding used in Inheritance
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.
• In other words, if a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.
• Method overriding is used for runtime polymorphism
Rules for Method Overriding
The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance)
‘super’ keyword
The super keyword is similar to this keyword.
• It is used to differentiate the members of super_class from the members of sub_class if they have same name.
• It is used to invoke the constructor of super_class from the sub_class. Usage of super Keyword
1. super is used to refer immediate parent class instance variable.
super.variable;
2. super is used to invoke immediate parent class method.
super.method();
3. super() is used to invoke immediate parent class constructor.
super();
super is used to refer immediate parent class instance variable
If a class is inheriting the properties of another class and if the members of the superclass have the
names same as the sub class, to differentiate these variables we use super keyword as shown below.
class Vehicle{
int speed = 50;
}
class Bike extends Vehicle{
int speed =100;
void display(){
System.out.println(super.speed);
}
public static void main(String args[]){
Bike b = new Bike();
b.display();
}
}
Output: ?
100