Java Reference
In-Depth Information
public Circle ( double r ) {
checkRadius ( r );
this . r = r ;
}
// Public data accessor methods
public double getRadius () { return r ; }
public void setRadius ( double r ) {
checkRadius ( r );
this . r = r ;
}
// Methods to operate on the instance field
public double area () { return PI * r * r ; }
public double circumference () { return 2 * PI * r ; }
}
public class PlaneCircle extends Circle {
// We automatically inherit the fields and methods of Circle,
// so we only have to put the new stuff here.
// New instance fields that store the center point of the circle
private final double cx , cy ;
// A new constructor to initialize the new fields
// It uses a special syntax to invoke the Circle() constructor
public PlaneCircle ( double r , double x , double y ) {
super ( r ); // Invoke the constructor of the superclass
this . cx = x ; // Initialize the instance field cx
this . cy = y ; // Initialize the instance field cy
}
public double getCentreX () {
return cx ;
}
public double getCentreY () {
return cy ;
}
// The area() and circumference() methods are inherited from Circle
// A new instance method that checks whether a point is inside the
// circle Note that it uses the inherited instance field r
public boolean isInside ( double x , double y ) {
double dx = x - cx , dy = y - cy ;
// Pythagorean theorem
double distance = Math . sqrt ( dx * dx + dy * dy );
return ( distance < r ); // Returns true or false
}
}
Instead of the preceding code, we can rewrite PlaneCircle using accessor methods,
like this:
Search WWH ::




Custom Search