Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java initializing classes without repeating myself

Tags:

java

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;
    }
}
like image 778
Christian Avatar asked Jul 21 '10 13:07

Christian


3 Answers

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;
    }
}
like image 176
leonbloy Avatar answered Nov 15 '22 07:11

leonbloy


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;
}
like image 33
BoltClock Avatar answered Nov 15 '22 07:11

BoltClock


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

like image 27
Bartek Jablonski Avatar answered Nov 15 '22 06:11

Bartek Jablonski