Java Reference
In-Depth Information
Car car = new Car("Ford", "Fiesta", 2009, 4);
car.describe();
}
}
Listing2-23 ' s Car classdeclaresa describe() methodthatoverrides Vehicle 's
describe() methodtooutputacar-orienteddescription.Thismethodusesreserved
word super to call Vehicle 's describe() method via super.describe(); .
Note Call a superclass method from the overriding subclass method by prefixing
themethod'snamewithreservedword super andthememberaccessoperator.Ifyou
don'tdothis,youenduprecursivelycallingthesubclass'soverridingmethod.Use su-
per and the member access operator to access non- private superclass fields from
subclasses that mask these fields by declaring same-named fields.
If you were to compile Listing 2-23 ( javac Vehicle.java ) and run the Car
application ( java Car ), you would discover that Car 's overriding describe()
methodexecutesinsteadof Vehicle 'soverridden describe() method,andoutputs
This car is a 2009 Ford Fiesta .
Caution Youcannot override a final method. Forexample, if Vehicle 's de-
scribe() method was declared as final void describe() , the compiler
wouldreportanerroruponencounteringanattempttooverridethismethodinthe Car
class. Developers declare their methods final when they do not want these meth-
ods to be overridden (for security or other reasons). Also, you cannot make an over-
ridingmethodlessaccessiblethanthemethoditoverrides.Forexample,if Car 's de-
scribe() methodwasdeclaredas private void describe() ,thecompiler
wouldreportanerrorbecauseprivateaccessislessaccessiblethanthedefaultpackage
access.However, describe() couldbemademoreaccessiblebydeclaringit pub-
lic , as in public void describe() .
Supposeyouweretoreplace Listing2-23 ' s describe() methodwiththemethod
shown here:
void describe(String owner)
{
System.out.print("This car, which is owned by "+owner+",
is a ");
Search WWH ::




Custom Search