Junior — Middle
Is it mandatory to call the constructor of the base class when creating a derived class?
sobes.tech AI
Answer from AI
In Java, when creating a subclass, calling the superclass constructor is mandatory, but it can be implicit. If the subclass constructor does not explicitly call the superclass constructor via super(), the compiler automatically inserts a call without arguments to the superclass constructor. However, if the superclass does not have a no-argument constructor, the superclass constructor must be explicitly called with the required arguments.
Example:
class Base {
Base(int x) { }
}
class Derived extends Base {
Derived() {
super(10); // mandatory call to superclass constructor with parameter
}
}
If the superclass has a no-argument constructor, the call to super() is automatically inserted, and explicitly writing it is not necessary.