Java initializes classes without repeating

Is it possible to rewrite the following a little more concise, that I do not need to repeat myself with the entry this.x = x; twice?

 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; } } 
+6
java
source share
5 answers

BoltClock's answer is the usual way. But some people (I) prefer the opposite "chain of constructors": configure the code in the most specific constructor (the same applies to ordinary methods) and make another call to those who have 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; } } 
+15
source share

Calling another constructor in this overloaded constructor using the this :

 public cls(int x, int y, int z){ this(x, y); this.z = z; } 
+10
source share
+1
source share

For this purpose you can use the initialization block.

0
source share

Very simple: just write the initialization as follows:

 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
source share

All Articles