Become a Pro in Java: Super Keyword in Java

Profile image for Jeffkeels
Jeffkeels Dotnet Developer
Jan 19, 2022 ‧ 1 min read

In Java, you can use a super keyword to declare a method as being an entry point into the class. A super keyword is used when you are defining a class and want to create an entry point into the class. This is usually useful when you have multiple classes that inherit from each other, like parent and child classes. The super keyword lets the child class call its parent's methods without actually having to go through the whole hierarchy of classes. Let’s learn a few more things about this Super keyword in Java. 

Usage of Java Super Keyword 

  • super can be used to refer to the immediate parent class instance variable. 
  • super can be used to invoke the immediate parent class method. 
  • super() can be used to invoke immediate parent class constructor 

1) super is used to refer to immediate parent class instance 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 TestSuper1{  
public static void main(String args[]){  
Dog d=new Dog();  
d.printColor();  
}}  

Output: 

black white 

 

2. Super can be used to invoke the immediate parent class method 

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 TestSuper2{  
public static void main(String args[]){  
Dog d=new Dog();  
d.work();  
}}  

Output: 

eating... barking... 

 

3. super() can be used to invoke immediate parent class constructor 

class Animal{  
Animal(){System.out.println("animal is created");}  
}  
class Dog extends Animal{  
Dog(){  
super();  
System.out.println("dog is created");  
}  
}  
class TestSuper3{  
public static void main(String args[]){  
Dog d=new Dog();  
}}  

Output: 

animal is created dog is created 
Posted on Jan 19, 2022 by:
Profile image for Jeffkeels
Jeffkeels
Dotnet Developer
AngularJava.NET

Comments

Profile image for Jeffkeels

Dotnet Developer

AngularJava.NET
1.3K
Reputation
113
Following
139
Followers