简体   繁体   中英

Java initializing classes without repeating myself

Is it possible 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;
}

您可以使用启动块来实现此目的。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM