class Base {
void test() {
System.out.println("base");
}
}
public class Derived extends Base {
void test() {
System.out.println("derived");
}
public static void main(String args[]) {
Derived d = new Derived();
Base b = (Base) d;
b.test();
}
}
o/p: derived
why? If I cast a subclass object to super class object super class object will refer to subclass object only?
Casting doesn't change the object at all. The result is just a reference to the same object, but with a different compile-time type. Casting to a super-type can't fail, it can only make a difference to the compile-time type of the expression, which can occasionally be useful for overload resolution.
In the same way, casting from an expression of a superclass type to a subclass type will never create a new object - it just checks whether the cast is valid, and the result is a reference to the same object as before, but in an expression with the subclass type. This is useful more often than casting to the superclass, as it gives you access to more members (usually). For example:
String text1 = "hello";
System.out.println(text1.length());
Object object = (Object) text1; // Or just Object object = text1;
// object.length() would be invalid...
String text2 = (String) object;
// text2.length() is valid again
System.out.println(text2.length());
The values of text1
, object
and text2
are all the same: a reference to the single string object which is used throughout the example.
See more on this question at Stackoverflow