Java – use “this” in another constructor
•
Java
Suppose you have a class with this constructor:
public SomeObj(int x,int y) { this.x = x; this.y = y; }
Everything is fine But now if you want to clone an object, I want the constructor to accept an argument with an object of that type, so you can copy all (necessary) fields in the constructor
public SomeObj(SomeObj objectToClone) { ... }
But now which two ways are better? What are the advantages and disadvantages (performance (bytecode), readability...)?
// 1 public SomeObj(SomeObj objectToClone) { this.x = objectToClone.x; this.y = objectToClone.y; } // 2 public SomeObj(SomeObj objectToClone) { this(objectToClone.x,objectToClone.y); }
Solution
Personally, I'll go with the latter
Where possible, I try to make a constructor have a "real" body and delegate it to all other builders This is not always possible - in particular, different constructors may need to be delegated to different super constructors - but it's nice to know that there's a place for additional initialization, logging, breakpoints, and so on
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码