Reputation: 931
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.
Upvotes: 2
Views: 1961
Reputation: 79838
You might consider using inheritance whenever there's an "is a" relationship between two classes - you might have a banking system with classes called Account
and SavingsAccount
- and a savings account is an account. Effectively, it means that any object of the subclass also belongs to the superclass.
But there's no such relationship between Integer
(32-bit integer) and Long
(64-bit integer). A 32-bit integer IS NOT A 64-bit integer; and a 64-bit integer IS NOT A 32-bit integer. So to suggest that there's an inheritance relationship between the Integer
class and the Long
class makes no sense.
Upvotes: 3
Reputation: 6258
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.
Upvotes: 3
Reputation: 649
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
.
Upvotes: 3