Home >Java >javaTutorial >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.
The above is the detailed content of Is `super()` Mandatory in Subclass Constructors?. For more information, please follow other related articles on the PHP Chinese website!