|
|
|
|
Assignment of Subclass and Superclass ObjectsBecause class Manager is a kind of Employee, we can refer to it using (staff[2] is of type Employee):
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:
Why?
|
|
This page was last modified on 02 October, 2007 |