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:
EDIT: The actual warning is "Access of private field of another object" and the only available action Netbeans offers is adding a @SuppressWarnings("AccessingNonPublicFieldOfAnotherObject")
My code is actually as trivial as the given example.
I see no problem with the code. In fact, I share your concerns and would prefer to not use getters.
What exactly is the warning you get? Maybe it is related to something you are not showing us?
Update: Seems Netbeans is really complaining about just that. That is a rather controversial warning to ship with an IDE, I would think.
It reminds me of the discussion ADT vs. Object.
ADT can access the internal state of other instance of the ADT. The object philosophy would prevent that and enforce access through getter/setter to ensure representation independence.
It's been a deliberated choice that instances variable in Java are class-private, not object-private (In the later case only this.privateInstVar
is allowed, not obj.privateInstVar
).
This has both strength and weaknesses. It's espcially handy when it comes to cloning and equality. On the other hand it can be misused and break encapsulation.
It's almost a philosophical debate. But IMHO, what you are doing is fine.
I don't know why NetBeans warns, but you are effectively making a shallow copy. Your copy shares field1, field2 and field3 with src and as such a modification of field3, say, a List, will reflect in the original.
private List field1;
public MyClass(MyClass src) {
this.field1 = src.field1;
this.field2 = src.field2;
this.field3 = src.field3;
field1.add(new Object()); // field1 of src also modified
...
}
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