Assume:
Double d = 12.0
Number n = (Number)d;
Question:
Is n become an instance type of Number?
public class InstanceTypeAfterCasting { /** * @param args the command line arguments */ public static void main(String[] args) { Double d = 12.0d; System.out.println("n type is Number " + Boolean.toString((Number)d instanceof Number));//1 System.out.println("n type is Double " + Boolean.toString((Number)d instanceof Double));//2 Number n = d;//3 Double m = (Double)n; //4 Double o = n; //5 } } //1 //2
The code above shows that d is still Number and Double after casting. So what casting means? it won't change the dynamic object type. it doesn't mean cutting off part from d object and leaving it like a Number object. Physically, d object haven't been altered after casting, but it tells compiler a specific scope, in which specific instance members are accessed. This is due to Java inheritance mechanism, where instance methods can be overridden and instance variable can be hidden in sub-classes.
//3
Number is the base class of Double; so it may assign a double to a Number. it reflects an IS-A relationship, i.e. d is a n.
//4
You cannot assign n to m directly, for Number is not a Double. then it needs a casting before assigning. In this case, Number's run-time object is indeed a double. So it is a valid casting.
//5
it causes a compiling error, for Number is not a Double, although Double is a Number.
Conclusion: casting should be a compiling notification.
//3
Number is the base class of Double; so it may assign a double to a Number. it reflects an IS-A relationship, i.e. d is a n.
//4
You cannot assign n to m directly, for Number is not a Double. then it needs a casting before assigning. In this case, Number's run-time object is indeed a double. So it is a valid casting.
//5
it causes a compiling error, for Number is not a Double, although Double is a Number.
Conclusion: casting should be a compiling notification.
No comments:
Post a Comment