Java Reference
In-Depth Information
Listing2-37 usesJava's abstract reservedwordtodeclareaclassthatcannotbe
instantiated. The compiler reports an error should you try to instantiate this class.
Tip Get into the habit of declaring classes that describe generic categories (e.g.,
shape,animal,vehicle,andaccount) abstract .Thisway,youwillnotinadvertently
instantiate them.
The abstract reservedwordisalsousedtodeclareamethodwithoutabody—the
compilerreportsanerrorwhenyousupplyabodyoromitthesemicolon.The draw()
method does not need a body because it cannot draw an abstract shape.
Caution The compiler reports an error when you attempt to declare a class that is
bothabstractandfinal.Forexample, abstract final class Shape isanerror
because an abstract class cannot be instantiated and a final class cannot be extended.
Thecompileralsoreportsanerrorwhenyoudeclareamethodtobeabstractbutdonot
declare its class to be abstract. For example, removing abstract from the Shape
class's header in Listing 2-37 results in an error. This removal is an error because a
non- abstract (concrete) class cannot be instantiated when it contains an abstract
method.Finally,whenyouextendanabstractclass,theextendingclassmustoverride
all the abstract class's abstract methods, or else the extending class must itself be de-
clared to be abstract; otherwise, the compiler will report an error.
An abstract class can contain non- abstract methods in addition to or instead of
abstract methods.Forexample, Listing2-22 ' s Vehicle classcouldhavebeende-
clared abstract . The constructor would still be present, to initialize private fields,
even though you could not instantiate the resulting class.
Downcasting and Runtime Type Identification
Moving up the type hierarchy via upcasting causes loss of access to subtype features.
Forexample,assigninga Circle instanceto Point variable p meansthatyoucannot
use p to call Circle 's getRadius() method.
However,itispossibletoonceagainaccessthe Circle instance's getRadius()
method by performing an explicit cast operation; for example, Circle c =
(Circle) p; .Thisassignmentisknownas downcasting becauseyouareexplicitly
movingdownthetypehierarchy(fromthe Point superclasstothe Circle subclass).
It is also an example of contravariance in that a type with a narrower range of values
( Point ) is being converted to a type with a wider range of values ( Circle ).
Search WWH ::




Custom Search