Search code examples
javanumberswrapperprimitiveautoboxing

Why do custom children of Number not inherit auto-boxing?


I understand that custom auto-boxing is not supported in Java, but I also noticed that I can extend the Number object. Since the number object itself seems to allow auto-boxing of primitives, this works:

Number val = 5; //This compiles no problem

If, however, I extend Number and try to use the child type, the program fails to compile:

MyNumber num = 5; //This does not compile :(

I understand this is not allowed and will probably never be allowed in Java, but what mechanism causes this discontinuity to occur? Is the wrapper functionality of Number handled somewhere beyond the class itself, or is there perhaps some special encapsulation that prevents custom wrapper creation?


Solution

  • 5 is an integer literal. Its type is thus int.

    Since it's assigned to a variable of a reference type (Number), it's autoboxed to its wrapper type: java.lang.Integer. This Integer is then assigned to the variable, and that's valid since Integer is a Number: the class Integer extends the class Number.

    On the contrary, Integer does not extend MyNumber. So the assignment of an Integer to a variable of type MyNumber is invalid: an Integer is not a MyNumber.

    So this doesn't have much to do with unboxing. It has to do with the fact that you can't do

    MyNumber n = someInteger;
    

    just like you can't so

    MyNumber n = someString;
    

    : the types are just not compatible.