Java Reference
In-Depth Information
// Compute average area of the shapes and
// average distance from the origin
double totalArea = 0 ;
double totalDistance = 0 ;
for ( int i = 0 ; i < shapes . length ; i ++) {
totalArea += shapes [ i ]. area (); // Compute the area of the shapes
// Be careful—in general, the use of instanceof to determine the
// runtime type of an object is quite often an indication of a
// problem with the design
if ( shapes [ i ] instanceof Centered ) { // The shape is a Centered shape
// Note the required cast from Shape to Centered (no cast would
// be required to go from CenteredSquare to Centered, however).
Centered c = ( Centered ) shapes [ i ];
double cx = c . getCenterX (); // Get coordinates of the center
double cy = c . getCenterY (); // Compute distance from origin
totalDistance += Math . sqrt ( cx * cx + cy * cy );
System . out . println ( "Average area: " + totalArea / shapes . length );
System . out . println ( "Average distance: " + totalDistance / shapes . length );
Interfaces are data types in Java, just like classes. When a class
implements an interface, instances of that class can be
assigned to variables of the interface type.
Don't interpret this example to imply that you must assign a CenteredRectangle
object to a Centered variable before you can invoke the setCenter() method or to
a Shape variable before you can invoke the area() method. CenteredRectangle
defines setCenter() and inherits area() from its Rectangle superclass, so you can
always invoke these methods.
Implementing Multiple Interfaces
Suppose we want shape objects that can be positioned in terms of not only their
center points but also their upper-right corners. And suppose we also want shapes
that can be scaled larger and smaller. Remember that although a class can extend
only a single superclass, it can implement any number of interfaces. Assuming we
have defined appropriate UpperRightCornered and Scalable interfaces, we can
declare a class as follows:
public class SuperDuperSquare extends Shape
implements Centered , UpperRightCornered , Scalable {
// Class members omitted here
Search WWH ::

Custom Search