public class Foo{
private String a;
private int b;
public Foo(Foo foo){
this.a = foo.a;
this.b = foo.b;
}
}
Hi eve
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);
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?
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