Here is my class that implements copy constructor
public class TestCopyConst
{
public int i=0;
public TestCopyConst(TestCopyConst tcc)
{
this.i=tcc.i;
}
}
i tried to create a instance for the above class in my main method
TestCopyConst testCopyConst = new TestCopyConst(?);
I am not sure what i should pass as parameter. If i have to pass a instance of TestCopyConst then again i have to go for "new" which in turn will again prompt for parameter
TestCopyConst testCopyConst = new TestCopyConst(new TestCopyConst(?));
what is missing here? or the concept of copy constructor is itself something different?
You're missing a constructor that isn't a copy constructor. The copy constructor copies existing objects, you need another way to make them in the first place. Just create another constructor with different parameters and a different implementation.
You need to also implement a no-arg constructor:
public TestCopyConst()
{
}
Or one that takes an i
:
public TestCopyConst(int i)
{
this.i = i;
}
Then, you can simply do this:
TestCopyConst testCopyConst = new TestCopyConst();
Or this:
TestCopyConst testCopyConst = new TestCopyConst(7);
Normally, your class will have a default no-arg constructor; this ceases to be the case when you implement a constructor of your own (assuming this is Java, which it looks like).
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