Java初始化类而不重复自己

Chr*_*ian 6 java

是否有可能更简洁地重写以下内容,我不必重复写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;
    }
}
Run Code Online (Sandbox Code Playgroud)

leo*_*loy 15

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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Bol*_*ock 10

使用this关键字调用此重载构造函数中的其他构造函数:

public cls(int x, int y, int z){
    this(x, y);
    this.z = z;
}
Run Code Online (Sandbox Code Playgroud)

  • 它被称为"构造链接" (2认同)