How does returning by enable access control? (Java) -
in java, when create getter private field of class follows(assume kid arraylist):
public arraylist getchild() { homecoming this.child; } you homecoming reference private field "name" (which means arraylist can modified using reference??) in c++, same kind of code homecoming copy, leave object's field unharmed if re-create manipulated.
can modify private fellow member calling method , modifying returned arraylist reference? if yes, how having getter in language java command access, then? , proper way write getter protect private members?
you homecoming reference private field "name"
well, not quite. homecoming current value of child field. it's of import understand that's not same somehow returning reference field itself. after method has returned, changes field (e.g. setting null, or making refer different list) not seen method caller. it's of import differentiate between field, reference (which value of field) , object reference refers to.
how having getter in language java command access, then?
it doesn't, directly.
and proper way write getter homecoming copy?
that depends on type. if utilize immutable types, don't need re-create anyway :)
for collections, potentially create read-only view on original collection - caller still see changes original collection. or can explicitly create own copy, e.g.
return new arraylist<>(child); java
No comments:
Post a Comment