Super Keyword in JAVA: The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of a subclass, an instance of the parent class is created implicitly which is referred by super reference variable.
Usage of Java Super Keyword:
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
1) super is used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of the parent class. It is used if parent class and child class have the same fields.
Class Animal {
String color="white";
}
class Dog extends Animal{
String color=”Black”;
void printColor(){
System.out.println(color);// print Dog Class color
System.out.println(super.color);//print color of Animal class
}
}
class Test{
public static void main(String args[]){
Dog d = new Dog();
d.printColor();
}}
output: Black white
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if subclass contains same method as parent class. In other words it is used if method is overridden.
Class Animal{
void eat(){
System.out.println(“eating..”);
}
}
class Dog extends Animal{
void eat(){System.out.println(eating bread”);}
void bark(){System.out.println(“barking”);}
void work(){
super.eat();
bark();
}
}
class Test{
public static void main(String args[]){
Dog d = new Dog();
d.work();
}
3) super is used to invoke parent class constructor
The super keyword can also be used to invoke parent class constructor.
Class Animal{
Animal(){System.out.println(“animal is created”);
}
}
class Dog extends Animal{
Dog(){super();
System.out.pringln(“dog is created”);
}
}
class Test{
public static void main(String args[]){
Dog d= new Dog();
}
}
Output:
animal is created dog is created
}
0 Comments