Java Reference
In-Depth Information
public static void main(String[] args)
Truck truck = new Truck("Chevrolet", "Silverado",
2011, true);
System.out.println("Make = "+truck.getMake());
System.out.println("Model = "+truck.getModel());
System.out.println("Year = "+truck.getYear());
Listing2-22 ' s Vehicle classdeclares private fieldsthatstoreavehicle'smake,
ter methods that retrieve these fields' values.
The Car subclassprovidesa private numWheels field,aconstructorthatinitial-
izes a Car object's Vehicle and Car layers, and a main() class method for test-
ingthisclass.Similarly,the Truck subclassprovidesa private isExtendedCab
field,aconstructorthatinitializesa Truck object's Vehicle and Truck layers,and
a main() class method for testing this class.
Car 'sand Truck 'sconstructorsusereservedword super tocall Vehicle 'scon-
structorwith Vehicle -orientedarguments,andtheninitialize Car 's numWheels and
Truck 's isExtendedCab instancefields,respectively.The super() callisanalog-
ous to specifying this() to call another constructor in the same class, but invokes a
superclass constructor instead.
Caution The super() callcanonlyappearinaconstructor.Furthermore,itmust
bethefirstcodethatisspecifiedintheconstructor.If super() isnotspecified,andif
because the subclass constructor must call a noargument superclass constructor when
super() is not present.
Car 's main() methodcreatestwo Car objects,initializingeachobjecttoaspecific
make, model, year,andnumberofwheels. Four System.out.println() method
callssubsequentlyoutputeachobject'sinformation.Similarly, Truck 's main() meth-
od creates a single Truck object, and also initializes this object to a specific make,
Search WWH ::

Custom Search