"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 > Is `super()` Mandatory in Subclass Constructors?

Is `super()` Mandatory in Subclass Constructors?

Published on 2024-11-08
Browse:953

Is `super()` Mandatory in Subclass Constructors?

Understanding the Necessity of super() in Subclass Constructors

When creating subclasses in Java, the question arises as to whether the super() method call is mandatory in the subclass's constructor. This article delves into this topic, providing clarity on the following aspects:

Automatic Insertion of super() by the Compiler

The short answer to this question is no. The compiler does not automatically insert a super() call in the subclass's constructor if it is not explicitly stated. Thus, the subclass constructor must always specify the superclass constructor it intends to invoke.

Non-Existence of No-Args Constructor Equivalents

It's important to understand that not putting a super() call in the subclass constructor does not imply that the compiler will insert an equivalent constructor without arguments. If the superclass does not have an accessible no-args constructor, omitting the super() call will result in a compilation error.

Constructor Invocation when Arguments are Present

Consider a subclass constructor with arguments. In this case, the super() call is required to specify which superclass constructor to invoke. The superclass constructor invoked is primarily determined by the actual arguments passed to the subclass's constructor. If no argument list is specified in the super() call, it will invoke the superclass constructor that matches the order and types of the subclass's construction arguments.

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