Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Object Typecasting
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Raknarg




PostPosted: Wed Feb 12, 2014 12:03 am   Post subject: Object Typecasting

Let's say I had a class, B which inherited from A.

Let's also say I had this function:

Java:

void doSomething(A obj) {
}


Inside the method would I be allowed to typecast to classes lower in the tree hierarchy? For instance:

Java:

void doSomething(A obj) {
    obj = (B)A;
}


Assuming what was passed in there was originally an object from B?
Sponsor
Sponsor
Sponsor
sponsor
Tony




PostPosted: Wed Feb 12, 2014 12:38 am   Post subject: Re: Object Typecasting

Technically you could.
Raknarg @ Wed Feb 12, 2014 12:03 am wrote:
Assuming what was passed in there was originally an object from B?

But the interface also allows for that object to be of type A.
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
DemonWasp




PostPosted: Wed Feb 12, 2014 3:01 am   Post subject: RE:Object Typecasting

Yes, you could do that. You could also use the instanceof operator to determine whether the argument is of the correct type. If it isn't, then casting it will generate a ClassCastException.

This is generally considered poor programming practice, and you would be better off designing your code to avoid this kind of scenario. The instanceof operator shouldn't show up in application code, and only very very rarely in library code.

You could, for example, overload the method with several different types as arguments: doSomething(A object), doSomething(B object). In that case, Java will use the the most specific option that it can choose at compile time. To be more specific, see http://stackoverflow.com/questions/385551/how-does-java-pick-which-overloaded-function-to-call
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: