Friday, 3 June 2016

does casting change variable type?

Principle: narrowing: when assigning a large data type(base type) to a type smaller one(child type); for instance, assigning a super-class type  to its sub-class type, or assigning a double primitive to a float; then it needs an explicit type casting.

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.


No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...