img
vol = shipment2.volume();
System.out.println("Volume of shipment2 is " + vol);
System.out.println("Weight of shipment2 is "
+ shipment2.weight);
System.out.println("Shipping cost: $" + shipment2.cost);
}
}
The output of this program is shown here:
Volume of shipment1 is 3000.0
Weight of shipment1 is 10.0
Shipping cost: $3.41
Volume of shipment2 is 24.0
Weight of shipment2 is 0.76
Shipping cost: $1.28
Because of inheritance, Shipment can make use of the previously defined classes of Box
and BoxWeight, adding only the extra information it needs for its own, specific application.
This is part of the value of inheritance; it allows the reuse of code.
This example illustrates one other important point: super( ) always refers to the constructor
in the closest superclass. The super( ) in Shipment calls the constructor in BoxWeight. The
super( ) in BoxWeight calls the constructor in Box. In a class hierarchy, if a superclass
constructor requires parameters, then all subclasses must pass those parameters "up the
line." This is true whether or not a subclass needs parameters of its own.
NOTE  In the preceding program, the entire class hierarchy, including Box, BoxWeight, and
OTE
Shipment, is shown all in one file. This is for your convenience only. In Java, all three classes
could have been placed into their own files and compiled separately. In fact, using separate
files is the norm, not the exception, in creating class hierarchies.
When Constructors Are Called
When a class hierarchy is created, in what order are the constructors for the classes that make up
the hierarchy called? For example, given a subclass called B and a superclass called A, is A's
constructor called before B's, or vice versa? The answer is that in a class hierarchy, constructors
are called in order of derivation, from superclass to subclass. Further, since super( ) must be the
first statement executed in a subclass' constructor, this order is the same whether or not super( )
is used. If super( ) is not used, then the default or parameterless constructor of each superclass
will be executed. The following program illustrates when constructors are executed:
// Demonstrate when constructors are called.
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home