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;
}
Read about constructor overloading http://www.javabeginner.com/learn-java/java-constructors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With