public class Foo{
private String a;
private int b;
public Foo(Foo foo){
this.a = foo.a;
this.b = foo.b;
}
}
Hi everyone.
I had this code in a small part I did at work.. My colleague saw this and gave me the "you-don't-deserve-to-breathe" look and went out for about 30 minutes to calm down. (I'm a fresh grad)
I've been trying to find out what is the shameful mistake I've made.. It was not successful.
Will somebody please explain exactly why is it a bad practice (or idiotic) to have this?
The reason I did this was that the class had many params, and I didn't want to have like 3 lines of parameters being passed (using primitive parameters) every time I needed to initialize this object.
And, FYI this object is (as we call it in work) a transaction object which is initialized whenever we need to pass around an entity class (it used instead of an entity class).
I do have a default constructor as well.
Thanks!
There is nothing wrong with your code. Actually what you did has a name: copy constructor And it is very convenient way to make o copy of another object. (assuming you have some other way to create instance of it besides this constructor )
You have only 1 constructor, so in order to create an object of class Foo, you need to pass to the constructor a Foo and in order to create that Foo you will need another Foo and it will go on and on . The code can make much more sense if for e.g. you will have a default constructor in the class and then you constructor
public Foo(Foo foo){
this.a = foo.a;
this.b = foo.b;
}
will act more like a Copy constructor in
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