Java Reference
In-Depth Information
Box does not override the methods getLength and getWidth , we can call these
methods of the class Rectangle without using the reserved word super .
public double area()
{
return
2 * (getLength() * getWidth()
+ getLength() * height
+ getWidth() * height);
}
The method volume of the class Box determines the volume of the box. To determine
the box's volume, you multiply the length, width, and height of the box or multiply the
area of the base of the box by its height. Let's write the definition of the method volume
by using the second alternative. To do so, you can use the method area of the class
Rectangle to determine the area of the base. Because the class Box overrides the
method area , to specify a call to the method area of the class Rectangle , we use the
reserved word super , as shown in the following definition:
public double volume()
{
return super .area() * height;
}
In the next section, we discuss how to specify a call to the constructor of the superclass
when writing the definition of a constructor of the subclass.
If a method of a class is declared final , it cannot be overridden in any subclass. The
following is an example of a final method:
public final void doAnything()
{
}
Constructors of the Superclass and Subclass
A subclass can have its own private data members, so a subclass can also have its own
constructors. A constructor typically serves to initialize the instance variables. When we
instantiate a subclass object, this object inherits the instance variables of the superclass, but
the subclass object cannot directly access the private instance variables of the superclass.
The same is true for the methods of a subclass. That is, the methods of the subclass cannot
directly access the private members of the superclass.
As a consequence, the constructors of the subclass can and should (directly) initialize only the
instance variables of the subclass. Thus, when a subclass object is instantiated, to initialize the
( private and other) instance variables—both its own and its ancestor class(es)—the subclass
object must also automatically execute one of the constructors of the superclass. A call to a
constructor of the superclass is specified in the definition of a subclass constructor by using
the reserved word super . The general syntax to call a constructor of a superclasss is:
super (parameters);
 
 
Search WWH ::




Custom Search