|
Re: casting super-class reference to a sub-class referenc
|
Posted: Mar 16, 2003 1:09 PM
|
|
Lets say, you have two classes, Person and Employee. Person is super class of Employee. The pseudocode is class Person { Other attributes and methods go here String getName()... }
class Employee extends Person { Other attributes and methods go here double getSalary () .... }
Let us say we have some method in some class, which will return us Person object as: Person p = get_person_object;
If you try to cast it to Employee then you will do as: Employee e = (Employee) p;
Since e is a refernce to Employee class you can very well call salary() method as: double sal = e.getSalary();
The code will compile fine. However, at runtime e will refer to an object to Peron class which doesn't have getSalary () method. And, your code e.getSalary() will blow up. Since an Employee is always a Person, but vice versa is not true, you should not do that. Otheriwse, you will error at runtime. SInce there is a potential danger that programmers may call some of the methods using subclass reference, which refers to super class object, and the method may not exist in super class at all, it is not allowed in Java. However, you can always cast subclass (in fact you can directly assign) subclass to super class and you are always safe.
Thanks Kishori
|
|