开发者

Java initializing classes without repeating myself

Is it p开发者_运维百科ossible to rewrite the following a bit more concise that I don't have to repeat myself with writing this.x = x; two times?

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's answer is the normal way. But some people (myself) prefer the reverse "constructor chaining" way: concentrate the code in the most specific constructor (the same applies to normal methods) and make the other call that one, with default argument values:

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;
    }
}


Call the other constructor within this overloaded constructor using the this keyword:

public cls(int x, int y, int z){
    this(x, y);
    this.z = z;
}


Read about constructor overloading http://www.javabeginner.com/learn-java/java-constructors


You can use initilization block for this purpose.


Very simple: Just write an initialize function like this:

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;  
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜