Reputation: 1
I start learning java after a relatively good experience in embedded C, and I try to apply some simple exercises to ensure the good understanding of java topics, This is a simple exercise , where I created a copy constructor to make a new object based on an existing one :
public class A {
private int a = 2;
private int b = 2;
public A(int a, int b) {
this.a = a;
this.b = b;
}
public A(A r) {
r.a=r.a + this.a;
r.b=r.b + this.b;
}
String getDetail() {
return "{"+a+","+b+"}";
}
public static void main(String[] args) {
A r = new A(1,1);
A a = new A(r);
System.out.println(a.getDetail());
}
}
And this is what I expect as an output : {3,3}
but this is what I obtained : {2,2}
Could you please explain why ? thanks in advance !
Upvotes: 0
Views: 364
Reputation: 31
The definition of a copy constructor is to ultimately copy the same characteristics of an instance specified as an argument to a new object of that class for example:
class Person {
private String name;
private int age;
public Person (String name, int age) {
this.name = name;
this.age = age;
}
public Person (Person person) {
this.name = person.name;
this.age = age;
}
}
Person john = new Person("John", 20);
Person johnDuplicated = new Person(john);
System.out.println(john.name + " " + john.age); //Output: John 20
System.out.println(johnDuplicated.name + " " + johnDuplicated.age); //Output: John 20
In your case you have already initialized the instance variables a and b by 2, this will allow for all instances of class A to be assigned with the value 2 by default for the mentioned instance variables. Proceeding to instantiate class A by providing:
A r = new A(1, 1);
A a = new A(r);
The above will produce {1,1} as output as you are referencing the parameter instance variables rather than the current instance variable (i.e. what the 'this' keyword represents) within the constructor of class A.
In order to allow for your desired behavior modify class A to the following:
public A (A r) {
this.a += r.a;
this.b += r.b;
}
Thus the output shall be:
{3,3}
Upvotes: 1
Reputation: 471
Your constructor is wrong, here is solution
public A(A r) {
this.a = r.a + this.a;
this.b = r.b + this.b;
}
But it is not a constructor of copy. Constructor of copy is
public A(A r) {
this.a = r.a;
this.b = r.b;
}
Upvotes: 0