Links

Java QA:Differentiate between upcasting & downcasting. Explain with reference of classes.

thanassis | Java Questions And Answers | Tuesday, January 2nd, 2007

In the object oriented world we have structures of objects made of classes. Classes can be ordered through a special inheritance relationship into hierarchies of parent/child relationships.

Upcasting means taking a reference to an object and changing its type to that of any of its parent classes. (for java, also all the interfaces that any of the parent classes may be implementing).


For example:

class A extends B{
}
class B{
}
class Program{
…….
B b = new B();
A a = (A) b; // this is upcasting!
…….
}

Upcasting in java is implicit. This means that we dont need the preceding parenthesis with the upcasting type.

A a = b;

would have equally worked. This is because we move away from something specific (class B – child) to something more general (class A – parent) and the java compiler can infer it.

Downcasting is the opposite:
…….
A a = new B(); // here we have an object from class B
// referenced to a variable of class A
// Implicit upcasting happens here.

B b = (B) a; // this is downcasting.

Downcasting must be explicit. If we try to downcast an object to a type that cant be downcasted to, then the compiler will protect us by giving us an error.
Otherwise our program would have crashed at runtime.

We can test with the operator instanceOf whether a downcast is safe.
For example:
if (a instanceOf (B)) {
b = (B)a;
}

The problem with “instanceOf” is that it creates a dependency in that segment of code and the type B. If in the future we create sibling to B classes we will have to remember to change all the places where we are checking with “instanceOf” and this can be a nightmare on a large system.

So, generally speaking, we want to create code that avoids downcasting. This is not always possible and not always a good idea as there are few cases where explicit downcasting is needed (for example when using containers) or is possible to use without problems (for example when we know there is no chance for extension or change).

No Comments

No comments yet.

Leave a comment

RSS feed for comments on this post. TrackBack URI