Java Reference
In-Depth Information
We haven't yet shown a syntax template for fields because we wanted to show
the preferred style with the fields private. The syntax for declaring encapsulated
fields is
private <type> <name>;
Fields can also be declared with an initial value:
private <type> <name> = <value>;
Declaring fields private encapsulates the state of the object, in the same way that
a radio's casing keeps the user from seeing the wires and circuitry inside it. Private
fields are visible to all of the code inside the Point class (i.e., inside the Point.java
file), but not anywhere else. This means that we can no longer directly refer to a
Point object's x or y fields in our client code. The following client code will not
compile successfully:
// this client code doesn't work with encapsulated points
System.out.println("p1 is (" + p1.x + ", " + p1.y + ")");
The compiler produces error messages such as the following:
PointMain.java:11: x has private access in Point
PointMain.java:11: y has private access in Point
To preserve the functionality of our client program, we need to provide a way for
client code to access a Point object's field values. We will do this by adding some
new accessor methods to the Point class. If the value of an object's field might be
useful externally, it is common to write an accessor to return that value. Here are the
methods that provide access to a Point object's x and y fields:
// returns the x-coordinate of this point
public int getX() {
return x;
}
// returns the y-coordinate of this point
public int getY() {
return y;
}
The client code to print a Point object's x and y values must be changed to the
following:
// this code works with our encapsulated Points
System.out.println("p1 is (" + p1.getX() + ", " + p1.getY() + ")");
 
Search WWH ::




Custom Search