
-----------------------------------
Raknarg
Wed Feb 12, 2014 12:03 am

Object Typecasting
-----------------------------------
Let's say I had a class, B which inherited from A.

Let's also say I had this function:


void doSomething(A obj) {
}


Inside the method would I be allowed to typecast to classes lower in the tree hierarchy? For instance:


void doSomething(A obj) {
    obj = (B)A;
}


Assuming what was passed in there was originally an object from B?

-----------------------------------
Tony
Wed Feb 12, 2014 12:38 am

Re: Object Typecasting
-----------------------------------
Technically you could.
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.

-----------------------------------
DemonWasp
Wed Feb 12, 2014 3:01 am

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
