[英]Java initializing classes without repeating myself
有沒有可能重寫以下更簡潔,我不必重復自己編寫this.x = x;
兩次?
public class cls{
public int x = 0;
public int y = 0;
public int z = 0;
public cls(int x, int y){
this.x = x;
this.y = y;
}
public cls(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
}
}
BoltClock的答案是正常的方式。 但是有些人(我自己)更喜歡反向的“構造函數鏈接”方式:將代碼集中在最具體的構造函數中(同樣適用於普通方法)並使另一個調用那個,使用默認參數值:
public class Cls {
private int x;
private int y;
private int z;
public Cls(int x, int y){
this(x,y,0);
}
public Cls(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
}
}
使用this
關鍵字調用此重載構造函數中的其他構造函數:
public cls(int x, int y, int z){
this(x, y);
this.z = z;
}
您可以使用啟動塊來實現此目的。
很簡單:只需編寫一個這樣的初始化函數:
public class cls{
public int x = 0;
public int y = 0;
public int z = 0;
public cls(int x, int y){
init(x,y,0);
}
public cls(int x, int y, int z){
init(x,y,z);
}
public void init(int x, int y, int z ) {
this.x = x;
this.y = y;
this.z = z;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.