Junior — Middle
What is the purpose of the super operator in the context of inheritance and calling methods or constructors of the base class?
sobes.tech AI
Answer from AI
The super operator in Java is used to refer to methods or constructors of the superclass (parent class) from a subclass.
Main purposes of super:
- Calling the constructor of the superclass from the subclass constructor to initialize the part of the object defined in the parent.
- Calling an overridden method of the superclass if the subclass needs to augment or change the behavior, but still retain some of the parent's logic.
Example of constructor usage:
class Animal {
String name;
Animal(String name) {
this.name = name;
}
}
class Dog extends Animal {
Dog(String name) {
super(name); // call to Animal constructor
}
}
Example of calling a superclass method:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
super.sound(); // call to superclass method
System.out.println("Bark");
}
}
Thus, super helps manage inheritance and reuse of the superclass code.