Referencing an Object's Fields
by, 04-26-2012 at 05:08 PM (888 Views)
Names are used to access the object fields. An unambiguous name shall be used.
Simple name could be used for the field, within class. For instance, a statement could be added in Rectangle class, which will be priting the height & width.
In this case simple names are height & width.Java Code:System.out.println("Width and height are: " + width + ", " + height);
Code that is being present out of the objectís class may utilize expression or the object reference that is being followed by (.) operator & ultimately following by simpler field name:
For instance, class CreateObjectDemo code is presnt out of the code, for Rectangle class. Hence, height, width or origin fields could be referred in the Rectangle objects which are known as rectOne. Class CreateObjectDemo shall be using names rectOne.width, rectOne.height and rectOne.origin. Among them, 2 names are used by the program so that to display the height and width of the rectOne.Java Code:objectReference.fieldName
Usage of simpler names height and width, from CreateObjectDemo class code doesnít actually make any sense. Because, these fields are present just in object and hence would be resulting into compiler errot.Java Code:System.out.println("Width of rectOne: " + rectOne.width); System.out.println("Height of rectOne: " + rectOne.height);
Later on same kind of code is used by the program for information display regarding rectTwo. Same kinds of objects consist of instance fieldís own copy. Hence fields named as height, width and origin are present in each Rectangle object. When an instance field is accessed via an object reference, particular field of object is reference.