Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having a class itself as its constructor's only parameter

Tags:

java

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!

like image 769
Amin Avatar asked Apr 18 '26 22:04

Amin


2 Answers

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 )

like image 103
Kamil.H Avatar answered Apr 20 '26 13:04

Kamil.H


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

like image 29
sol4me Avatar answered Apr 20 '26 11:04

sol4me