Junior — Middle
What is the role and purpose of the 'super' keyword in Java?
sobes.tech AI
Answer from AI
The keyword super in Java is used to refer to members (methods or fields) of the superclass from a subclass. It allows:
- Calling the superclass constructor from the subclass constructor (
super()), which is mandatory if the superclass does not have a no-argument constructor. - Accessing superclass methods if they are overridden in the subclass, for example,
super.methodName(). - Accessing superclass fields if they are hidden by fields with the same name in the subclass.
Example:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void sound() {
super.sound(); // call to superclass method
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
}
}
Output:
Animal sound
Bark