Java Reference
In-Depth Information
From Figure 10-6, it follows that the class es Scanner , Reader , and Writer are derived
from the class Object . The class InputStreamReader is derived from the class
Reader , and the class FileReader is derived from the class InputStreamReader .
Similarly, the class PrintWriter is derived from the class Writer .
Polymorphism
Java allows us to treat an object of a subclass as an object of its superclass. In other words, a
reference variable of a superclass type can point to an object of its subclass. There are
situations when this feature of Java can be used to develop generic code for a variety of
applications.
Consider the following statements. (The class es Person and PartTimeEmployee are as
previously defined.)
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
The statement in Line 1 declares name and nameRef to be reference variables of type
Person . Similarly, the statement in Line 2 declares employee and employeeRef to be
reference variables of type PartTimeEmployee . The statement in Line 3 instantiates the
object name and the statement in Line 4 instantiates the object employee .
Now consider the following statements:
nameRef = employee;
//Line 5
System.out.println("nameRef: " + nameRef);
//Line 6
The statement in Line 5 makes nameRef point to the object employee . After the
statement in Line 5 executes, the object nameRef is treated as an object of the class
PartTimeEmployee . The statement in Line 6 outputs the value of the object nameRef .
The output of the statement in Line 6 is:
nameRef: Susan Johnson's wages are: $562.5
Notice that even though nameRef is declared as a reference variable of type Person ,
when the program executes, the statement in Line 6 outputs the first name, the last name,
and the wages of a PartTimeEmployee . This is because when the statement in Line 6
executes to output nameRef , the method toString of the class PartTimeEmployee
executes, not the method toString of the class Person . This is called late binding,
dynamic binding,orrun-time binding; that is, the method that gets executed is
determined at execution time, not at compile time.
 
Search WWH ::




Custom Search