If both objects are of the same type, you can use factory methods:
public class Foo { ... public Foo withBar(...) { Foo f = new Foo(this.param); f.setBar(...); return f; } public Foo withBaz(...) { Foo f = new Foo(this.param); f.setBaz(...); return f; } } ... Foo y = ...; Foo x = y.withBar(...);
If the types are different, you can make factory static methods and pass Y as a parameter.
source share