This program generates the following output:
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076
Volume of mybox3 is -1.0
Weight of mybox3 is -1.0
Volume of myclone is 3000.0
Weight of myclone is 34.3
Volume of mycube is 27.0
Weight of mycube is 2.0
Pay special attention to this constructor in BoxWeight( ):
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}
Notice that super( ) is passed an object of type BoxWeight--not of type Box. This still
invokes the constructor Box(Box ob). As mentioned earlier, a superclass variable can be
used to reference any object derived from that class. Thus, we are able to pass a BoxWeight
object to the Box constructor. Of course, Box only has knowledge of its own members.
Let's review the key concepts behind super( ). When a subclass calls super( ), it is calling
the constructor of its immediate superclass. Thus, super( ) always refers to the superclass
immediately above the calling class. This is true even in a multileveled hierarchy. Also, super( )
must always be the first statement executed inside a subclass constructor.
A Second Use for super
The second form of super acts somewhat like this, except that it always refers to the superclass
of the subclass in which it is used. This usage has the following general form:
super.member
Here, member can be either a method or an instance variable.
This second form of super is most applicable to situations in which member names of
a subclass hide members by the same name in the superclass. Consider this simple class
hierarchy:
// Using super to overcome name hiding.
class A {
int i;
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home