Can I define a default constructor in Java?

My question below is more theoretical than practical. From many of the available Java resources, I learned that the default constructor for a class has the following specification:

  • does not accept arguments
  • doesn't have throws suggestions
  • has an empty body

The Java language specification does not contain a definition for the default constructor , it only claims that

If the class (definition) does not contain constructor declarations, then by default the constructor is declared implicitly (by the compiler).

Note that the implicitly declared implies that an explicitly set default constructor is possible. Let's look at the class below:

 public class Point { private int x; private int y; public int getX() { return x; } public int getY() { return y; } } 

For this class, the compiler will generate a lower default constructor:

 public Point() { super(); } 

My question is: if I, as a programmer, implemented the constructor as public Point() { } , could it be called the default constructor for the class above Point? If not, can any explicitly defined constructor be considered a default constructor ? I appreciate the answer from someone who is an expert or absolutely sure about this topic.

-3
source share
1 answer

If you explicitly define any constructor, then it cannot be the default constructor, even if you encode code that is exactly equivalent to the default constructor generated by the compiler. The default value here means the absence of any programmer actions in you.

UPDATE: OP wants evidence based answer

Compiler rules from section 13.4.12. Method and constructor declarations (JLS8):

  • If you do not declare any constructors in your class, the default constructor is generated by the compiler.

Evidence. If the source code for a non-inner class does not contain declared constructors, then the default constructor without parameters is declared implicitly (ยง8.8.9).

  1. If you declare one or more constructors in your class, even if it is a no-arg constructor and is akin to the compiler created by the default constructor, your explicit constructor will replace the default constructor created by the compiler. To emphasize this, your explicit no-arg constructor, which is equivalent to that generated by the compiler, is not a generated compiler.

Evidence. Adding one or more constructor declarations to the source code of such a class will prevent the implicit declaration of this constructor by default, effectively deleting the constructor if only one of the new constructors also has no parameters, thereby replacing the default constructor.

+5
source

All Articles