The Artima Developer Community
Sponsored Link

Java Answers Forum
casting super-class reference to a sub-class referenc

1 reply on 1 page. Most recent reply: Mar 16, 2003 1:09 PM by Kishori Sharan

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
johnson

Posts: 1
Nickname: sanioor
Registered: Mar, 2003

casting super-class reference to a sub-class referenc Posted: Mar 16, 2003 2:01 AM
Reply to this message Reply
Advertisement
i wanted to know why casting super-class reference to a sub-class referenc is dangerous
thanx


Kishori Sharan

Posts: 211
Nickname: kishori
Registered: Feb, 2002

Re: casting super-class reference to a sub-class referenc Posted: Mar 16, 2003 1:09 PM
Reply to this message Reply
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

Flat View: This topic has 1 reply on 1 page
Topic: Java resolve symbol  error Previous Topic   Next Topic Topic: Java Internals

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use