class One
{
void show1()
{
System.out.println("super class");
}
}
class Two extends One
{
static void show2()
{
System.out.println("subclass");
}
}
public class Cast
{
public static void main(String[] args)
{
One o=(One) new Two();
o.show1();
}
}
How does this statement work in this code One o=(One) new Two(); ? Why can’t I use like this
Two o=(One) new Two(); ? I am confused of using casting, though o here is super class variable.. Why can’t I refer sub class method using o?
It means that an object of class
Twois created and pointed by referenc of classOne. Type casting is not required.That is polymorphism. derived class can’t point to base class.
Rule of thumb: Base class can point to any derived class. (not vice-versa). So, you can cast a derived class to base class and not other way round.
Right, but the actual object is of derived class and the reference is of base class. Only those methods of derived class will be accessible which are overriden in derived class.
Try following lines of code to see yourself:
See this: ClassCastException, ClassCastException, and Explanation of "ClassCastException" in Java