"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Do Java Subclasses Always Need to Explicitly Call the Superclass Constructor?

Do Java Subclasses Always Need to Explicitly Call the Superclass Constructor?

Published on 2024-11-09
Browse:765

Do Java Subclasses Always Need to Explicitly Call the Superclass Constructor?

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

  • No-args constructor: A constructor with no parameters.
  • Accessible no-args constructor: A no-args constructor in the superclass that is visible to the subclass (public, protected, or package-private).
  • Default constructor: The public no-args constructor added by the compiler when there is no explicit constructor in the class.

When is super() Required?

Using super() explicitly is only required if:

  • The superclass does not have an accessible no-args constructor.
  • The subclass constructor includes parameters, in which case it must explicitly call a constructor in the superclass that accepts those parameters.

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.

Latest tutorial More>

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