Junior — Middle
Can you explain what the keyword 'super' means in the context of object-oriented programming?
sobes.tech AI
Answer from AI
The super keyword in Java is used to refer to members (methods or fields) of the superclass from a subclass. It allows:
- Calling the constructor of the parent class from the constructor of the child class.
- Accessing methods or fields of the parent class if they are overridden in the child.
Example of using super:
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");
}
Dog() {
super(); // call to superclass constructor
}
}
Thus, super helps manage inheritance and overriding, providing access to the parent class's functionality.