Computer Science Canada Object Typecasting |
Author: | Raknarg [ 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:
Inside the method would I be allowed to typecast to classes lower in the tree hierarchy? For instance:
Assuming what was passed in there was originally an object from B? |
Author: | Tony [ 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. |
Author: | DemonWasp [ 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 |