I can understand what upcasting is but Downcasting is a little confusing. My question is why should we downcast? Can you help me with a real time example ? Is downcasting th
One place you need it is if you override the equals
method inherited from Object
. Since the parameter passed to the method is of type Object
, you have to cast it to the type of the class to be able to access methods and variables defined in it. Just pay special attention to what referred to object is. That is to say, instantiated object is passed to the equals()
method, not its reference.
class MySuperClass
{
private int num1;
public MySuperClass() {}
public MySuperClass(int num1)
{
this.num1 = num1;
}
}
class MySubClass extends MySuperClass
{
private int num;
public MySubClass(int num)
{
this.num = num;
}
public boolean equals(Object o)
{
if (!(o instanceof MySubClass))
return false;
MySubClass mySub = (MySubClass)o;
return(mySub.num == num);
}
public static void main(String[] args)
{
Object mySub = new MySubClass(1);
MySuperClass mySup = new MySubClass(1);
System.out.println(mySub.equals(mySup));
}
}