メインジェネレータ、サブジェネレータ
private int position = 0;
private Position(int position) {
this.position = position;
}
public static Position createStartPosition() {
return new Position(START_POSITION_VALUE);
}
静的工場法はよくできている.👍今はpositionを直接初期化する部分がなくてもいいですよね?😁
直接初期化部分はprivate int position=0です.この部分は正しいですか?
上記のとおりです。読者に余地を残したくないなら、直接初期化すべきではないでしょうか.
メッセージを残すとき、コードにはデフォルトのコンストラクション関数(空のコンストラクション関数)があるのを覚えています.
private int position;
public Position() {
}
この場合、positionの初期化値を明確に決定してほしい.デフォルトのコンストラクション関数は存在せず、静的ファクトリメソッドで処理されます.
ファクトリメソッドは、プライマリジェネレータを使用して初期化されます.
したがってposition=0コードは動作に影響しません.
また,Positionが不変のオブジェクトになるとコンパイルもエラーとなる.
と言った以上、メインジェネレータを勉強しましょうか?
メインジェネレータ、サブジェネレータ
生成者は
primary constructor
とsecondary constructor
である.名前の通り、プライマリ・ジェネレータはプライマリ・ジェネレータであり、
secondary constructor
はプライマリ・ジェネレータを呼び出すためのステップにすぎない.final class Cash {
private final int cents;
private final String currency;
public Cash() { // secondary
this(0);
}
public Cash(int cts) { // secondary
this(cts, "USD");
}
public Cash(int cts, String crn) { // primary
this.cents = cts;
this.currency = crn;
}
// methods here
}
メインジェネレータは1つのみで、残りはsecondary constructor**이다.
次構造関数는
this(...)ロールは、プライマリジェネレータを呼び出すことによって行われます.構成の良いクライソンは、プライマリジェネレータが1つしかなく、すべての
secondary constructor
の後に発表する必要があります.その理由は,コードの重複を減らすためである.メインジェネレータがない場合
final class Cash {
private final int cents;
private final String currency;
public Cash() { // primary
this.cents = 0;
this.currency = "USD";
}
public Cash(int cts) { // primary
this.cents = cts;
this.currency = "USD";
}
public Cash(int cts, String crn) { // primary
this.cents = cts;
this.currency = crn;
}
// methods here
}
普通は私が作ったコードです.実際、IntellieJでジェネレータを作成するのは、ショートカットキー(Alt+Ins)を押すのが簡単なので、あまり面倒ではありません.しかし、読者の立場から見ると、これはあまりにも繰り返しです.https://www.yegor256.com/2015/05/28/one-primary-constructor.html
Reference
この問題について(メインジェネレータ、サブジェネレータ), 我々は、より多くの情報をここで見つけました https://velog.io/@injoon2019/주-생성자-부-생성자テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol