Polymorphism
Home ] Up ] What is Inheritance? ] Inheritance versus Containment ] Superclasses & Subclasses ] Visibility Modifiers & Inheritance ] Final Classes & Methods ] [ Polymorphism ] Data Hiding & Encapsulation ] Abstract Classes ] Interfaces ] Cloning Objects ] The Collections Framework ] Interfaces & Callbacks ]

 

Method Parameters

 

Assignment of Subclass and Superclass Objects

Because class Manager is a kind of Employee, we can refer to it using (staff[2] is of type Employee):

staff[2] = new Manager("Mother Theresa",
                       120000,
                       new Date(89, 3, 5),
                       "Demi Moore");

but we can't call Manager-specific methods through that reference:

String sec = staff[2].getSecretaryName(); // Error

Java gives a compilation error:

Error: Method getSecretaryName() not found in Employees.Employee

If we know that it really is a Manager, then we can cast it:

String sec = ((Manager)staff[2]).getSecretaryName();

but if it really isn't a Manager,

String sec = ((Manager)staff[0]).getSecretaryName();

then Java throws an exception at run time:

java.lang.ClassCastException

It's best to try to restrict this kind of casting only to within code that is hidden from the outside world!

In general, you can assign a superclass object to a subclass object:

Employee colleague = new Manager();

but not the other way around:

Manager colleague = new Employee(); // Error

In this case, Java gives a compile-time error:

Error: Incompatible type for vardeclaration. 
   Explicit cast needed to convert Employees.Employee 
   to Employees.Manager

Why?

 

This page was last modified on 02 October, 2007