Super Keyword in Java
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 subclass, an instance of parent class is created implicitly which is referred
by super reference variable.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color of Animal class
}
}
class TestSuper {
public static void main(String args[]) {
Dog d=new Dog();
d.printColor();
}
}
void eat() {
System.out.println("eating...");
void eat() {
System.out.println("eating bread...");
void bark() {
System.out.println("barking...");
void work() {
super.eat();
bark();
class TestSuper {
d.work();
• In the above example Animal and Dog both classes have eat() method if we call eat() method from
Dog class, it will call the eat() method of Dog class by default because priority is given to local.
• To call the parent class method, we need to use super keyword.
As we know well that default constructor is provided by compiler automatically if there is no constructor.
But, it also adds super() as the first statement.
Another example of super keyword where super() is provided by the compiler implicitly.
class Animal{
Animal(){
System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper{
public static void main(String args[]){
Dog d=new Dog();
}
}