Java Reference
In-Depth Information
After the statement in Line 12 executes,
shapeRef
points to the object
box
. The
statement in Line 13 executes the method
toString
. Because
shapeRef
points to an
object of the
class
BoxFigure
, the method
toString
of the
class
BoxFigure
executes. When the method
toString
of the
class
BoxFigure
executes, it also executes
the method
area
. In this case, the method
area
of the
class
BoxFigure
executes, which
outputs the surface area of the box.
If a method of a
class
is declared final, it cannot be overridden with a new definition in
a derived class. You declare a method of a class final by using the keyword
final
. For
example, the following method is final:
public final void
doSomeThing()
{
//...
}
Similarly, you can also declare a
class
final using the keyword
final
. If a class is
declared final, then no other
class
can be derived from this
class
; that is, it cannot be
the superclass of any other classes.
Java does not use late binding for methods that are marked
private
,
final
,or
static
.
As illustrated above, a reference variable of a superclass type can point to an object of its
subclass. However, you cannot automatically consider a superclass object to be an object
of a subclass. In other words, you cannot automatically make a reference variable of a
subclass type point to an object of its superclass.
Suppose that
supRef
is a reference variable of a superclass type. Moreover, suppose that
supRef
points to an object of its subclass. You can use an appropriate cast operator on
supRef
and make a reference variable of the subclass point to the object. On the other
hand, if
supRef
does not point to a subclass object and you use a cast operator on
supRef
to make a reference variable of the subclass point to the object, then Java will throw a
ClassCastException
—indicating that the
class
cast
is not allowed.
Suppose
name
,
nameRef
,
employee
, and
employeeRef
are as declared in the begining of
this section, that is:
1
0
Person name, nameRef;
//Line 1
PartTimeEmployee employee, employeeRef;
//Line 2
name =
new
Person("John", "Blair");
//Line 3
employee =
new
PartTimeEmployee("Susan", "Johnson",
12.50, 45);
//Line 4
nameRef = employee;
//Line 5
Now consider the following statement:
employeeRef = (PartTimeEmployee) name;
//Illegal
Search WWH ::
Custom Search