Having a class itself as its constructor's only parameter

前端 未结 4 1951
星月不相逢
星月不相逢 2021-01-20 09:51
public class Foo{
    private String a;
    private int b;

    public Foo(Foo foo){
        this.a = foo.a;
        this.b = foo.b;
    }
}

Hi eve

相关标签:
4条回答
  • 2021-01-20 10:00

    Constructor get calls when you want to create an instance using new keyword. All the classes have a default constructor which is like classname(){}

    In your example you have a separate constructor. Therefore the default constructor is no longer exist for your class. The only constructor that you have now is

    public Foo(Foo foo){}
    

    According to the your source you must pass an instance of Foo to create an new instance of Foo class. So you can try

    Foo fooObj = new Foo(new Foo(new Foo(.......))
    

    As you can see that this will never get end.

    You can pass null as the parameter to constructor

    Foo fooObj = new Foo(null)
    

    But since you are using the instance variables of reference Foo object to initiate the values of new Foo object it will not work either.

    What you should do is add the default constructor to your class.

    public class Foo{
        private String a;
        private int b;
    
        public Foo(){}
    
        public Foo(Foo foo){
            this.a = foo.a;
            this.b = foo.b;
        }
    }
    

    Then you can create instances of Foo class as follows

    Foo f1 = new Foo();
    f1.setA("ABC"); // create getters and setters
    f1.setB(12);
    
    Foo f2 = new Foo(f1);
    
    0 讨论(0)
  • 2021-01-20 10:05

    This is nonse code. You need instance of class to create instance... How you want to create the first instance of this object at all?

    0 讨论(0)
  • 2021-01-20 10:16

    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 )

    0 讨论(0)
  • 2021-01-20 10:17

    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

    0 讨论(0)
提交回复
热议问题