Vivek
Vivek

Reputation: 57

Why doesn't java.lang.Integer extend java.lang.Long?

It is possible to assign an integer value into a long variable. It is possible to autobox an integer value into a Long reference variable. But it is not possible to assign an Integer object to a Long reference variable.

My view is an Integer / integer is a specific range of values that Long / long supports.

So the hierarchy should be Integer extends Long and Long extends Number.

Views invited.

Upvotes: 3

Views: 1420

Answers (2)

Bohemian
Bohemian

Reputation: 425073

The reason is simple: If Integer extended Long, then instances of Integer would be instances of Long too:

Integer i = 0;
if (i instanceof Long) 
    // yes! oops... Integer would be a Long

Clearly, this is not the case mathematically and should not be the case.

Do not confuse types sharing a range of values with a case for having the types share a class hierarchy.


Discussions regarding storage etc are implementation detail and not relevant to the language design considerations this question is about.

Upvotes: 4

Eran
Eran

Reputation: 393846

A Long contains a long member (value) that contains the value of that Long.

If Integer was a sub-class of Long, Integer would either use that long member of the base class, which is wasteful (since long takes twice as many bytes as int), or ignore it and use its own int member, which would be even more wasteful (since in that case the Integer class would contain both the int member and the long member of the base class).

The boxed versions of the primitive types should be as efficient as possible (since you are forced to use them in some cases, such as Collections, which can't hold primitives directly). Therefore any class hierarchy that would increase the storage of the Integer class seems like a bad idea.

Upvotes: 8

Related Questions