Java Reference
In-Depth Information
figure 4.14
An abstract Shape
class. Figures 4.12
and 4.13 are
unchanged.
1 public abstract class Shape
2 {
3 public abstract double area( );
4 public abstract double perimeter( );
5
6 public double semiperimeter( )
7 { return perimeter( ) / 2; }
8 }
A class that has at least one abstract method is an abstract class . Java
requires that all abstract classes explicitly be declared as such. When a
derived class fails to override an abstract method with an implementation, the
method remains abstract in the derived class. As a result, if a class that is not
intended to be abstract fails to override an abstract method, the compiler will
detect the inconsistency and report an error.
An example of how we can make Shape abstract is shown in Figure 4.14.
No changes are required to any of the other code in Figures 4.12 and 4.13.
Observe that an abstract class can have methods that are not abstract, as is the
case with semiperimeter .
An abstract class can also declare both static and instance fields. Like
nonabstract classes, these fields would typically be private, and the instance
fields would be initialized by constructors. Although abstract classes cannot
be created, these constructors will be called when the derived classes use
super . In a more extensive example, the Shape class could include the coordi-
nates of the object's extremities, which would be set by constructors, and it
could provide implementation of methods, such as positionOf , that are inde-
pendent of the actual type of object; positionOf would be a final method.
As mentioned earlier, the existence of at least one abstract method
makes the base class abstract and disallows creation of it. Thus a Shape object
cannot itself be created; only the derived objects can. However, as usual, a
Shape variable can reference any concrete derived object, such as a Circle or
Rectangle . Thus
A class with at least
one abstract
method must be an
abstract class .
Shape a, b;
a = new Circle( 3.0 ); // Legal
b = new Shape( ); // Illegal
Before continuing, let us summarize the four types of class methods:
1.
Final methods . The virtual machine may choose at run time to per-
form inline optimization, thus avoiding dynamic dispatch. We use a
final method only when the method is invariant over the inheritance
hierarchy (that is, when the method is never redefined).
 
Search WWH ::




Custom Search