Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 867
Vivek Avatar asked Sep 01 '26 13:09

Vivek


1 Answers

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.

like image 121
Eran Avatar answered Sep 04 '26 03:09

Eran