Access of private field of another object in copy constructors - Really a problem?

Posted by DR on Stack Overflow See other posts from Stack Overflow or by DR
Published on 2010-03-12T09:24:05Z Indexed on 2010/03/12 9:27 UTC
Read the original article Hit count: 219

In my Java application I have some copy-constructors like this

public MyClass(MyClass src) {
    this.field1 = src.field1;
    this.field2 = src.field2;
    this.field3 = src.field3;
...
}

Now Netbeans 6.9 warns about this and I wonder what is wrong with this code?

My concerns:

  • Using the getters might introduce unwanted side-effects. The new object might no longer be considered a copy of the original.
  • If it is recommended using the getters, wouldn't it be more consistent if one would use setters for the new instance as well?

© Stack Overflow or respective owner

Related posts about java

Related posts about encapsulation