Java Reference
In-Depth Information
class().createReturnType();
System.out.println(suprt); // Output: superclass re-
turn type
SubReturnType subrt = (
SubReturnType
) new Sub-
class().createReturnType();
System.out.println(subrt); // Output: subclass return
type
}
}
In
Listing 2-41
, the first bolded code reveals an upcast from
SubReturnType
to
SuperReturnType
, and the second bolded code uses the required
(SubReturnType)
cast operator to downcast from
SuperReturnType
to
SubReturnType
, prior to the assignment to
subrt
.
Formalizing Class Interfaces
Inmyintroductiontoinformationhiding,Istatedthateveryclass
X
exposesan
interface
(a protocol consisting of constructors, methods, and [possibly] fields that are made
available to objects created from other classes for use in creating and communicating
with
X
's objects).
Java formalizes the interface concept by providing reserved word
interface
,
whichisusedtointroduceatypewithoutimplementation.Javaalsoprovideslanguage
featurestodeclare,implement,andextendinterfaces.Afterlookingatinterfacedeclar-
ation,implementation,andextension,thissectionexplainstherationaleforusinginter-
faces.
Declaring Interfaces
Aninterfacedeclarationconsistsofaheaderfollowedbyabody.Atminimum,thehead-
erconsistsofreservedword
interface
followedbyanamethatidentifiestheinter-
face. The body starts with an open brace character and ends with a close brace. Sand-
wichedbetweenthesedelimitersareconstantandmethodheaderdeclarations.Consider
Listing 2-42.
Declaring a
Drawable
interface