java - Modification of a private class attribute only with getter -
i read article: combination of getter , list modification in java
and wonder if modification on types of class attributes possible access via getter. tried integer object
public class someclass { private integer someinteger = 9; public integer getsomeinteger() { return someinteger; // id = 18, value = 9 } }
now try modify someinteger in 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 debugger inspect object id. in calling class someinteger first has same id in getter. after adding 1, someinteger new id , original class attribute not edited.
okay try adding number failed, there possibility modify object?
i asked me difference between linked example list , example integer. idea is,
someinteger += 1;
internally creates new integer object. in contrast list has own modification methods, not causes instantiation of new list object. right? follow data types self modifying methods can access getter have protected modifying other classes?
your issue not implementing proper setter, , integer
immutable.
so doing when incrementing someinteger
right incrementing value of reference someinteger
scoped method executing increment, without impacting on private field.
a setter method takes argument, , internally sets field's value, after validation if applicable.
so setter should like:
public void setsomeinteger(int value) { // todo validate if applicable someinteger = value; }
then invoke as:
someclassinstance.setsomeinteger(42);
Comments
Post a Comment