3.23.Referencing an Object's Fields
Object fields are accessed by their name. You must use a name that is unambiguous.
You may use a simple name for a field within its own class. For example, we can add a statement within the Rectangle class that prints the width and height:
System.out.println(“Width and height are: ” + width + “, ” + height);
In this case, width and height are simple names.
Code that is outside the object’s class must use an object reference or expression, followed by the dot (.) operator, followed by a simple field name, as in:
For example, the code in the CreateObjectDemo class is outside the code for the Rectangle class. So to refer to the origin, width, and height fields within the Rectangle object named rectOne, the CreateObjectDemo class must use the names rectOne.origin, rectOne.width, and rectOne.height, respectively. The program uses two of these names to display the width and the height of rectOne:
System.out.println(“Width of rectOne: ” + rectOne.width);System.out.println(“Height of rectOne: ” + rectOne.height);
Attempting to use the simple names width and height from the code in the CreateObjectDemo class doesn’t make sense — those fields exist only within an object — and results in a compiler error.
Later, the program uses similar code to display information about rectTwo. Objects of the same type have their own copy of the same instance fields. Thus, each Rectangle object has fields named origin, width, and height. When you access an instance field through an object reference, you reference that particular object’s field. The two objects rectOne and rectTwo in the CreateObjectDemo program have different origin, width, and height fields.
To access a field, you can use a named reference to an object, as in the previous examples, or you can use any expression that returns an object reference. Recall that the new operator returns a reference to an object. So you could use the value returned from new to access a new object’s fields:
int height = new Rectangle().height;
This statement creates a new Rectangle object and immediately gets its height. In essence, the statement calculates the default height of a Rectangle. Note that after this statement has been executed, the program no longer has a reference to the created Rectangle, because the program never stored the reference anywhere. The object is unreferenced, and its resources are free to be recycled by the Java Virtual Machine.