Java Reference
In-Depth Information
The statement in Line 1 creates the Rectangle object myRectangle . Thus, the object
myRectangle has two instance variables: length and width . The statement in Line 2
creates the Box object myBox . Thus, the object myBox has three instance variables:
length , width , and height (see Figure 10-4).
length
width
6
myRectangle
length
width
5
myBox
5
3
height
4
FIGURE 10-4 Objects myRectangle and myBox
Consider the following statements:
System.out.println(myRectangle); //Line 3
System.out.println(myBox); //Line 4
In the statement in Line 3, the method toString of the class Rectangle is executed;
in the statement in Line 4, the method toString associated with the class Box is
executed. Recall that if a subclass overrides a method of the superclass, the redefinition
applies only to the objects of the subclass. Thus, the output of the statement in Line 3 is:
Length = 5.0; Width = 3.0
The output of the statement in Line 4 is:
Length = 6.0; Width = 5.0; Height = 4.0
A call to a constructor of a superclass is specified in the definition of a constructor of the
subclass. When a subclass constructor executes, first a constructor of the superclass executes
to initialize the data members inherited from the superclass and then the constructor of the
subclass executes to initialize the data members declared by the subclass. So first the
constructor of the class Rectangle executes to initialize the instance variables length
and width and then the constructor of the class Box executes to initialize the instance
variable height .
The program in Example 10-2 shows how the objects of a superclass and a base class work.
EXAMPLE 10-2
Consider the following Java application program:
// This program illustrates how the objects of a superclass and a
// base class work.
 
Search WWH ::




Custom Search