Copy Instance Instance Instance

Here is my class that implements the copy constructor

public class TestCopyConst { public int i=0; public TestCopyConst(TestCopyConst tcc) { this.i=tcc.i; } } 

I tried to create an instance for the specified class in my main method

 TestCopyConst testCopyConst = new TestCopyConst(?); 

I am not sure what I should pass as a parameter. If I need to pass an instance of TestCopyConst, then again I need to switch to "new", which, in turn, will again offer a parameter

 TestCopyConst testCopyConst = new TestCopyConst(new TestCopyConst(?)); 

what is missing here? or is the concept of a copy constructor in itself something else?

+4
source share
5 answers

You are missing a constructor that is not a copy constructor. The copy constructor copies existing objects, you need another way to do them first. Just create another constructor with different parameters and a different implementation.

+4
source

You also need to implement the no-arg constructor:

 public TestCopyConst() { } 

Or one that accepts i :

 public TestCopyConst(int i) { this.i = i; } 

Then you can simply do this:

 TestCopyConst testCopyConst = new TestCopyConst(); 

Or that:

 TestCopyConst testCopyConst = new TestCopyConst(7); 

Normally your class will have a no-arg constructor by default; this ceases to be the case when you implement your own constructor (assuming that it is Java, what it looks like).

+2
source

You should use the Copy Constructor as an overloaded constructor to clone the object, but you also need another constructor to initialize the instance in the usual way:

 public class TestCopyConst { public int i=0; public TestCopyConst(int i) { this.i = i; } public TestCopyConst(TestCopyConst tcc) { this.i=tcc.i; } } 
+1
source

Is the concept of copy constructor something else? "

There are no copy constructors in Java, as is the case with C ++, that is, they are automatically generated and / or called by the compiler. You can define it yourself, but it can only be used if you call it. Not the same, long chalk.

I am not sure what I should pass as a parameter. If I need to pass an instance of TestCopyConst, then again I need to switch to "new", which, in turn, will again offer a parameter

Here you prove the point. The only thing you can pass to the copy constructor is another instance of the same class (or derived class ...). If you don't have another copy instance, why do you think you need a copy constructor at all?

+1
source

You need

 public class TestCopyConst { public int i=0; public TestCopyConst(TestCopyConst tcc) { this.i=tcc.i; } public TestCopyConst(int val) { i = val; } //or public TestCopyConst() { } } 
0
source

Source: https://habr.com/ru/post/1301783/


All Articles