java - What is the proper way to access an objects instance-objects instance-variable -
let's have 2 constructor classes; person , arm.
public class person { private arm arm; //instance variable public person(arm arm) //constructor { this.arm = arm; } } -
public class arm { private int fingers; //instance variable public arm(int fingers) //constructor { this.fingers = fingers; } public int getfingers() { return this.fingers(); } } every person object has arm object instance-variable. every arm object has int instance-variable called fingers.
what proper way access fingers variable?
1. create getfingers() method, in person class:
//in person.java public int getfingers() { return this.arm.getfingers(); //this refrencing getfingers() method in arm class } so can access this:
arm myarm = new arm(5); person me = new person(myarm); system.out.println(me.getfingers()); create method in person returns arm.
public arm getarm() { return this.arm; }
so can use getfingers method arm class this:
arm myarm = new arm(5); person me = new person(myarm); system.out.println(me.getarm().getfingers())
normally suggest law of demeter comes play here.
- each unit should have limited knowledge other units: units "closely" related current unit.
- each unit should talk friends; don't talk strangers.
- only talk immediate friends.
if write:
a = new a(); d d = a.getb().getc().getd(); then allow access d instance of a but breaks encapsulation , reveals a has b, b has c etc. etc. might argue redundant in case, since expect person have arm.
an alternative approach think want top-level object (person) do, , tell you. e.g. if want fingers can tell them grasp (perhaps) then:
person.pickup(object) and person can determine how (it choose arm, or it's feet or mouth in extreme situations!). rather fingers yourself, you're telling object you. oop about.
Comments
Post a Comment