Java Reference
In-Depth Information
With the point in mind that a subclass guarantees at least the same behavior (methods) as its superclass, let's
consider the following snippet of code:
Employee emp;
emp = new Manager(); // A Manager object assigned to an Employee variable
emp.setName("Richard Castillo");
String name = emp.getName();
The compiler will compile the above snippet of code too, even though you have changed the code this time to
assign the emp variable an object of the Manager class. It will pass the setName() and getName() method calls on the
same basis as described in the previous case. It also passes the assignment statement
emp = new Manager();
The compile-time type of “ new Manager() ” expression is the Manager type. The compile-time type (or declared type)
of the emp variable is Employee type. Since the Manager class inherits from the Employee class, an object of the Manager
class “is-a” object of the Employee class. Simply, you say that a manager is always an employee. Such an assignment
(from subclass to superclass) is called upcasting and it is always allowed in Java. It is also called a widening conversion
because an object of the Manager class (more specific type) is assigned to a reference variable of the Employee type
(a more generic type). All of the following assignments are allowed and they are all examples of upcasting:
Object obj;
Employee emp;
Manager mgr;
PartTimeManager ptm;
// An employee is always an object
obj = emp;
// A manager is always an employee
emp = mgr;
// A part-time manager is always a manager
mgr = ptm;
// A part-time manager is always an employee
emp = ptm;
// A part-time manager is always an object
obj = ptm;
Use a simple rule to check if an assignment is a case of upcasting. Look at the compile-time type (declared type) of the
expression on the right side of the assignment operator (e.g. b in a = b ). If the compile-time type of the right hand operand
is a subclass of the compile-time type of the left-hand operand, it is a case of upcasting, and the assignment is safe and
allowed. Upcasting is a direct technical translation of the fact that an object of a subclass “is-a” object of the superclass, too.
Upcasting is a very powerful feature of inheritance. It lets you write polymorphic code that works with classes that
exists and classes that will be added in future. It lets you code your application logic in terms of a superclass that will
always work with all subclasses (existing subclasses or subclasses to be added). It lets you write generic code without
worrying about a specific type (class) with which the code will be used at runtime. Listing 16-4 is a simple utility class
to test your upcasting rule. It has a printName() static method that accepts an argument of the Employee type.
The printName() method uses the getName() method of the Employee class to get the name of the employee object
and prints the name on the standard output.
 
Search WWH ::




Custom Search