Super Keyword :
The super keyword in Java is used to refer to the immediate parent class object.
The super keyword refers to superclass (parent) objects.
It is used to call superclass methods, and to access the superclass constructor.
The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.
To understand the super keyword, you should have a basic understanding of Inheritance and Polymorphism.
class Animal {
String name = "Animal";
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
String name = "Dog";
void sound() {
System.out.println("Dog barks");
}
void show() {
// Access parent variable
System.out.println("Parent name: " + super.name);
// Call parent method
super.sound();
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.show();
}
}
OUTPUT:
Parent name: Animal
Animal makes a sound
---------------------------------------------
super.name → gets the parent class variable.
super.sound() → calls the parent class method.
Reference:
https://www.datacamp.com/doc/java/super
https://www.w3schools.com/java/ref_keyword_super.asp
https://www.scholarhat.com/tutorial/java/super-keyword-in-java
Top comments (0)