General speaking, if the left hand side of an assignment is a more specific type (subtype) and the right hand side is a more general type (supertype), then explicit casting is required. On the other hand, when you assign a subclass reference to a variable of superclass, the casting is performed automatically, or not required.
Another case is calling methods from an object reference, you can not access methods that are only declared and implemented in its subclass. You have to explicit cast the object reference into the actual object type.
For example,
class Super { } class Sub extends Super { public void writeLog() { System.out.println("log"); }
class Program { public static void main(String[] args) { Sub b = new Sub(); // sub type reference can be assigned to super type without casting Super a = b; // super type reference has to be casted before assigned to sub type b = (Sub)a; ((Sub)a).writeLog(); // method only defined in sub type } }
Java compiler is not responsible for checking if the casting is correct or not, just like some of the bindings only occur at run time ( Run time binding or compile time binding?). Java virtual machine does the checking at run time to find out whether the actual reference object is a legitimate object of the new type. If not, there will be a runtime exception: ClassCastException.
Comments
Post a Comment