Can I define `default constructor` in Java?

自古美人都是妖i 提交于 2019-12-25 19:42:09

问题


My question below is rather theoretical then practical. From many Java resources available online I found out that a default constructor for a class has below specification:

  1. takes no arguments
  2. has no throws clauses
  3. has an empty body

Java language specification does not provide definition for default constructor, it only states that

If a class (definition) contains no constructor declarations, then a default constructor is implicitly declared (by a compiler).

Please notice that wording implicitly declared implies that the explicitly defined default constructor is possible. Lets consider below class:

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 below default constructor:

public Point() {
  super();
}

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


回答1:


If you explicitly define any constructor, then it cannot be a default constructor, even if you code one that is exactly equivalent to default constructor generated by the compiler. Default, here, means in the absence of any action by you the programmer.

UPDATE: OP wants an answer based on evidence

Compiler Rules from Section 13.4.12 Method and Constructor Declarations (JLS8):

  1. If you declare no constructors in your class, then a default constructor is generated by the compiler.

Evidence: If the source code for a non-inner class contains no declared constructors, then a default constructor with no parameters is implicitly declared (§8.8.9).

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

Evidence: Adding one or more constructor declarations to the source code of such a class will prevent this default constructor from being implicitly declared, effectively deleting a constructor, unless one of the new constructors also has no parameters, thus replacing the default constructor.



来源:https://stackoverflow.com/questions/29681791/can-i-define-default-constructor-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!