Java Reference
In-Depth Information
super.describe();
}
The modified Car class now has two describe() methods, the preceding ex-
plicitly declared method and the method inherited from Vehicle . The void de-
scribe(String owner) method does not override Vehicle 's describe()
method. Instead, it overloads this method.
TheJavacompilerhelpsyoudetectanattempttooverloadinsteadofoverrideameth-
odatcompiletimebylettingyouprefixasubclass'smethodheaderwiththe @Over-
ride annotation, as shown below—I discuss annotations in Chapter 3 :
@Override
void describe()
{
System.out.print("This car is a ");
super.describe();
}
Specifying @Override tellsthecompilerthatthemethodoverridesanothermethod.
Ifyouoverloadthemethodinstead,thecompilerreportsanerror.Withoutthisannota-
tion,thecompilerwouldnotreportanerrorbecausemethodoverloadingisavalidfea-
ture.
Tip Get into the habit of prefixing overriding methods with the @Override an-
notation. This habit will help you detect overloading mistakes much sooner.
I previously presented the initialization order of classes and objects, where you
learnedthatclassmembersarealwaysinitializedfirst,andinatop-downorder(thesame
orderappliestoinstancemembers).Implementationinheritanceaddsacouplemorede-
tails:
• Asuperclass'sclassinitializersalwaysexecutebeforeasubclass'sclassinitial-
izers.
• Asubclass'sconstructoralwayscallsthesuperclassconstructortoinitializean
object's superclass layer before initializing the subclass layer.
Java's support for implementation inheritance only permits you to extend a single
class. You cannot extend multiple classes because doing so can lead to problems. For
example,supposeJavasupportedmultipleimplementationinheritance,andyoudecided
tomodela flying horse (fromGreekmythology)viatheclassstructureshownin Listing
2-24 .
Search WWH ::




Custom Search