I read this article: Combination of getter and list modification in Java
and now I wonder if a modification on all types of class attributes is possible only by access via a getter. I tried with an Integer object
public class SomeClass
{
private Integer someInteger = 9;
public Integer getSomeInteger()
{
return someInteger; // id = 18, value = 9
}
}
Now I try to modify someInteger in another Class:
SomeClass someClass = new SomeClass();
Integer someInteger = someClass.getSomeInteger(); // id = 18, value = 9
someInteger += 1; // id = 26, value = 10
Integer anotherInteger = someClass.getSomeInteger(); // id = 18, value = 9
With a debugger I inspect the object id. In my calling class someInteger first has the same ID as in the getter. After adding a 1, someInteger get a new id and the original class attribute is not edited.
Okay my try with adding a number failed, but is there a possibility to modify the originally object?
I asked me about the difference between the linked example with a List and my example with an Integer. My idea is, that
someInteger += 1;
internally creates a new Integer object. In contrast the list has its own modification methods, which not causes the instantiation of a new List object. Is this right? From this it would follow that all data types with self modifying methods that I can access by a getter have to be protected from modifying by other classes?