Java Reference
In-Depth Information
defined to return 0.0. In practice, since the superclass Shape should never be
instantiated, only the subclasses, then the superclass getArea() will never be
called anyway.
The capability to reference instances of Rectangle and Circle as Shape
types uses the advantage of polymorphism (see Section 4.2.1) in which a set of
different types of shapes can be treated as one common type. For example, in the
following code, a Shape array passed in the parameter list contains references
to different types of subclass instances:
void double aMethod (Shape[] shapes) {
areaSum = 0.0;
for (int i = 0; i < shapes.length; i++) {
areaSum + = shapes[i].getArea ();
}
}
This method calculates the sum of all the areas in the array with a simple loop
that calls the getArea() method for each instance. The polymorphic feature
means that the subclass-overriding version of getArea() executes, not that of
the base class.
The careful reader will have observed that the technique used above is messy
and error-prone. There is no way, for instance, to require that subclasses override
getArea() . And there is no way to ensure that the base class is never instantiated.
The above scheme works only if the subclasses and the users of the Shape class
follow the rules. Suppose someone does instantiate a Shape base class and then
uses its getArea() method to calculate pressure, as in the force per unit area.
Since the area is 0.0, the pressure will be infinite (or NaN ). The Java language
can do much better than that.
A much better way to create such a generic base class is to declare a method
abstract . This makes it explicit that the method is intended to be overridden.
In fact, all abstract methods must be overridden in some subclass or the compiler
will emit errors. No code body is provided for an abstract method. It is just a
marker for a method signature, including return type, that must be overridden
and given a concrete implementation in some subclass.
In the above case, we add the abstract modifier to the getArea() method
declaration in our Shape class and remove the spurious code body as shown
here:
public abstract class Shape {
abstract double getArea ();
}
Search WWH ::




Custom Search