Java MCQ: Can a class inherit constructors from its superclass in Java?
Answer:
Explanation:
In Java, constructors are not inherited by subclasses. A constructor is a special method used to initialize objects, and it has the same name as the class. When a subclass is created, it does not inherit the constructor of its superclass; instead, it must define its own constructor. However, a subclass can call the constructor of its superclass using the super
keyword, typically within its own constructor, to ensure that the superclass’s properties are initialized before the subclass’s.
For example:
class Animal {
Animal() {
System.out.println("Animal constructor called");
}
}
class Dog extends Animal {
Dog() {
super(); // Calls the Animal constructor
System.out.println("Dog constructor called");
}
}
In this example, the Dog
class does not inherit the Animal
constructor. Instead, it explicitly calls the superclass’s constructor using super()
. The output when creating a Dog
object would be:
Animal constructor called
Dog constructor called
This behavior ensures that the superclass is properly initialized before the subclass adds its own initialization. It’s important to understand this concept because it affects how objects are constructed and initialized in an inheritance hierarchy, and it highlights the importance of the super
keyword in constructor chaining.