Define default constructor for record

丶灬走出姿态 提交于 2020-05-24 20:16:56

问题


I have a record and want to add default constructor to it.

public record Record(int recordId) {
   public Record {

   }
}

But it created constructor with int param.

public final class Record extends java.lang.Record {
    private final int recordId;
    public Record(int);
    //other method
}

How can we add a default constructor to a record?


回答1:


To split hairs, you cannot ever define a default constructor, because a default constructor is generated by the compiler when there are no constructors defined, thus any defined constructor is by definition not a default one.

If you want a record to have a no-arg constructor, records do allow adding extra constructors or factory methods, as long as the "canonical constructor" that takes all of the record fields as arguments is called.

public record Record(int recordId) {
   public Record() {
      this(0); 
   }
}



回答2:


Explicit constructor

In your case, you can explicitly specify a no-argument constructor with the delegation to the canonical constructor with a default value if you want to and this can be done as -

public Record(){
    this(Integer.MIN_VALUE);
}

In short, any non-canonical constructor should delegate to one, and that should hold true for the data-carrying nature of these representations.

Compact Constructor

On the other hand, note that the representation you had used in your code.

public Record {}

is termed as a "compact constructor" which represents a constructor accepting all arguments and that can also be used for validating the data provided as attributes of the record. A compact constructor is an alternate way of declaring the canonical constructor.



来源:https://stackoverflow.com/questions/61152337/define-default-constructor-for-record

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