Java Reference
In-Depth Information
Suppose that class C is a subclass of class B and that class B is a subclass of
class A . Then, a reference variable of class A can point to an object of class B as
well as to an object of class C . Thus, a reference variable of a superclass can point to an
object of any of its descendent classes.
In a class hierarchy, several methods may have the same name and the same formal
parameter list. Also, a reference variable of a class can refer to either an object of its own
classoranobjectofitssubclass.Therefore,areferencevariablecaninvoke,thatis,
execute, a method of its own class or of its subclass(es). Binding means associating a
method definition with its invocation, that is, determining which method definition
gets executed. In early binding, a method's definition is associated with its invocation
whenthecodeiscompiled.Inlate binding, a method's definition is associated with the
method's invocation at execution time, that is, when the method is executed. Except
for a few (special) cases (noted following Example 10-5), Java uses late binding for all
methods. Furthermore, the term polymorphism means associating multiple (potential)
meanings with the same method name. In Java, polymorphism is implemented using
late binding.
The reference variable name or nameRef can point to any object of the class Person or the
class PartTimeEmployee . Loosely speaking, we say that these reference variables have
many forms, that is, they are polymorphic reference variables. They can refer to objects of
their own class or to objects of the subclasses inherited from their class.
The following example further illustrates polymorphism.
EXAMPLE 10-5
1
0
public class RectangleFigure
{
private double length;
private double width;
public RectangleFigure()
{
length = 0;
width = 0;
}
public RectangleFigure( double l, double w)
{
setDimension(l, w);
}
public void setDimension( double l, double w)
{
if (l >= 0)
length = l;
 
Search WWH ::




Custom Search