Java Reference
In-Depth Information
public class PlaneCircle extends Circle {
// Rest of class is the same as above The field r in
// the superclass Circle can be made private because
// we no longer access it directly here
// Note that we now use the accessor method getRadius()
public boolean isInside ( double x , double y ) {
double dx = x - cx , dy = y - cy ; // Distance from center
double distance = Math . sqrt ( dx * dx + dy * dy ); // Pythagorean theorem
return ( distance < getRadius ());
}
}
Both approaches are legal Java, but they have some differences. As we discussed in
“Data Hiding and Encapsulation” on page 121 , fields that are writable outside of the
class are usually not a correct way to model object state. In fact, as we will see in
“Safe Java Programming” on page 195 and again in “Java's Support for Concur‐
rency” on page 208 , they can damage the running state of a program irreparably.
It is therefore unfortunate that the protected keyword in Java allows access to fields
(and methods) from both subclasses and classes in the same packages as the declar‐
ing class. This, combined with the ability for anyone to write a class that belongs to
any given package (except system packages), means that protected inheritance of
state is potentially flawed in Java.
O n
Java does not provide a mechanism for a member to be visible
only in the declaring class and its subclasses.
For all of these reasons, it is usually better to use accessor methods (either public or
protected) to provide access to state for subclasses—unless the inherited state is
declared final , in which case protected inheritance of state is perfectly permissible.
Singleton
The singleton pattern is another well-known design pattern. It is intended to solve
the design issue where only a single instance of a class is required or desired. Java
provides a number of different possible ways to implement the singleton pattern. In
our discussion, we will use a slightly more verbose form, that has the benefit of
being very explicit in what needs to happen for a safe singleton:
public class Singleton {
private final static Singleton instance = new Singleton ();
private static boolean initialized = false ;
// Constructor
private Singleton () {
super ();
Search WWH ::




Custom Search