Sing Sandibar
Sing Sandibar

Reputation: 714

Practical uses of downcasting

I've finished reading the chapters on polymorphism and inheritance and done all the exercises in my Java books. But I still don't understand why I would need to use downcasting in practice. Could you please give some examples from work or projects where you had to use downcasting?

Upvotes: 0

Views: 468

Answers (1)

AllTooSir
AllTooSir

Reputation: 49372

Suppose you have a base class, and a class that derives from that base class either directly or indirectly. Then, anytime an object of that base class type is type cast into a derived class type, it is called a Downcast. You need to downcast to make an instance specific. For example, let getobject() be a method which returns an Object, since String is a subclass of Object, this method may return a String as well.

Case (i):

Object o = getObject();

Here you have assigned the object returned by the method to an Object reference variable. So you can invoke only the methods defined in Object class on the instance o.

Case (ii):

Object o = getObject();
if(o instanceof String)
  String s = (String)o;

Here, if getobject() actually had returned a String instance, then you are downcasting it to String. The advantage of this is that you can invoke methods defined in String on s which you couldn't have done in Case(i).

Upvotes: 1

Related Questions