Junior — Middle
Mis on super operaatori funktsioon pärimise ja baasklasside meetodite või konstruktorite kutsumise kontekstis?
sobes.tech AI
Vastus AI-lt
The super operator in Java is used to access methods or constructors of the superclass (parent class) from a subclass.
Main purposes of super:
- Calling the constructor of the superclass from the constructor of the subclass to initialize the part of the object defined in the parent.
- Calling an overridden method of the superclass if the subclass needs to supplement or modify the behavior, while preserving part 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");
}
}
This way, super helps manage inheritance and reuse of superclass code.