Java MCQ: What is the purpose of the ‘super’ keyword in Java?
Answer:
Explanation:
The super
keyword in Java is used to refer to the immediate parent class of an object. It serves several important functions, such as calling the constructor of the parent class, accessing parent class methods, and referencing parent class fields when they are hidden by subclass fields.
One of the most common uses of super
is in constructors. When a subclass is instantiated, the constructor of the parent class is automatically invoked. If a specific parent constructor needs to be called, super()
is used to make that call, ensuring that the parent class is properly initialized before the subclass adds its own initialization:
class Animal {
Animal(String name) {
System.out.println("Animal constructor called with name: " + name);
}
}
class Dog extends Animal {
Dog(String name) {
super(name); // Calls the Animal constructor
System.out.println("Dog constructor called");
}
}
In this example, when a Dog
object is created, the super(name)
call invokes the constructor of the Animal
class, passing the name as a parameter. This ensures that the Animal
part of the Dog
object is initialized first.
In addition to constructors, super
is also used to call overridden methods from the parent class or access hidden fields. This is particularly useful in cases where the subclass has overridden a method, but you still need to call the parent class’s version of that method.