Must You Explicitly Call the Superclass Constructor in Java Subclasses?
When defining a subclass, it's common practice to see constructors that explicitly call the superclass constructor using super(). However, one may question if this is necessary.
Is super() Automatically Added by the Compiler?
Yes, if the subclass constructor omits a call to the superclass constructor, the compiler will automatically call the accessible no-argument constructor (no-args constructor) in the superclass. This default behavior is known as constructor chaining.
Types of Constructors
When is super() Required?
Using super() explicitly is only required if:
Example 1:
public class Base {}
public class Derived extends Base {}
No explicit call to super() is needed because Base has a default constructor.
Example 2:
public class Base {
public Base(int i) {}
}
public class Derived extends Base {
public Derived(int i) {
super(i); // Explicitly call the Base(int) constructor
}
}
In this case, super(i) is required because the superclass does not have a no-args constructor, and the subclass constructor needs to provide an initial value for its i parameter.
By understanding these concepts, you can avoid unnecessary super() calls and ensure proper constructor chaining in your subclasses.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3