Java Reference
In-Depth Information
Notice that both constructors perform similar actions; the only difference is what
initial values the x and y fields receive. Another way of saying this is that the new
constructor can be expressed in terms of the old constructor. The following two lines
construct equivalent objects:
Point p1 = new Point(); // construct Point at (0, 0)
Point p2 = new Point(0, 0); // construct Point at (0, 0)
A common programming practice when writing classes with multiple constructors
is for one constructor to contain the true initialization code and for all other construc-
tors to call it. This means that every object created passes through a common code
path. This system can be useful when you are testing and debugging your code later.
The syntax for one constructor to call another is to write the keyword this , followed
by the parameters to pass to the other constructor in parentheses:
this(<expression>, <expression>, ..., <expression>);
This is really just the normal syntax for a method call, except that we use the spe-
cial keyword this where we would normally put the name of a method. In our case,
we want to pass parameter values of 0 and 0 to initialize each field:
// constructs a new point at the origin, (0, 0)
public Point() {
this(0, 0); // calls Point(int, int) constructor
}
8.4 Encapsulation
Our next version of the Point class will protect its data from unwanted access using
a concept known as encapsulation.
Encapsulation
Hiding the implementation details of an object from the clients of the object.
To understand the notion of encapsulation, recall the analogy of radios as objects.
Almost everyone knows how to use a radio, but few people know how to build a
radio or understand how the circuitry inside a radio works. It is a benefit of the
radio's design that we don't need to know those details in order to use it.
The radio analogy demonstrates an important dichotomy of external versus inter-
nal views of an object. From the outside, we just see behavior. From the inside, we
see the internal state that is used to accomplish that behavior (Figure 8.1).
Focusing on the radio's external behavior enables us to use it easily while ignoring
the details of its inner workings that are unimportant to us. This is an example of an
important computer science concept known as abstraction.
 
 
Search WWH ::




Custom Search