Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't Java's number classes extend each other?

In Java, why don't the built-in number classes extend each other? Shouldn't Long extend Integer which extends Short which extends Byte, and Double extend Float?

In general, inheritance is often used when there's an "is a" relationship. So is every Integer a Long? I think so.

The only possible explanation I can think of is that overflow won't be handled correctly. For example, (byte)100 + (byte)100 is -112, whereas (short)100 + (short)100 is 200. However, it seems that there should be a better reason than preserving buggy behavior.

like image 796
Ypnypn Avatar asked Nov 30 '25 07:11

Ypnypn


2 Answers

You question can really be approached in two different ways:

If we are talking about primitives, then you have the relationship backwards.

But, if you are asking about the Integer, Double, Long, etc. classes, then there is a relationship between all the numbers.

It's important to point out that numbers as objects in Java stem from a common Number class found here. It doesn't make much sense to break them down in the hierarchy like how you described because the methods between all the numbers are essentially the same, despite the varying sizes in memory they take up.

In short, hierarchies in Java are defined by the relationships (typically methods) that classes share, not the size they take up in memory.

like image 51
James Taylor Avatar answered Dec 01 '25 20:12

James Taylor


Because there is nothing to inherit. Each of the types listed are their own separate entity. Inheritance can't be used to "extend" an 8-bit value to a 32-bit one, for example. Anything that they do have in common is inherited from java.lang.Number.

like image 27
Andy Senn Avatar answered Dec 01 '25 20:12

Andy Senn