Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the Number class doesn't have methods like add() or negate()?

Tags:

java

numbers

Well, this is a question about the Java design.

Why aren't there methods like add() and negate() on the java.lang.Number class, but there are on some of its subclasses?

I mean... there is no uniformity. I can use the + or - operators on Float, Long and other autoboxeable classes, and I can use add() and negate() on BigDecimal or BigInteger (which violates the SRP).

So if we are allowing those operations on Byte/Short/Integer/Long anyways (with autoboxing and operators), why not just add an abstract Number negate() and etc to Number?

Is there a reason for this?

like image 993
paulotorrens Avatar asked Jan 18 '14 01:01

paulotorrens


People also ask

Can a class have no methods?

There is no class which doesn't have any method. All Classes are subclass of Object class. So all the methods from Object class are inherited.

How many times a method can be invoked in a Java program?

Core Java bootcamp program with Hands on practice It is invoked only once during the execution of a program. Following are some notable points about the finalize method. Since this method belongs the Object class, which is the super class of all the classes in java, you can override it from any class.

What does class <> mean in Java?

What Does Class Mean? A class — in the context of Java — is a template used to create objects and to define object data types and methods.

What is method body in Java?

The method body is where all of the action of a method takes place; the method body contains all of the legal Java instructions that implement the method. Within the method body, you can use this to refer to the current object. The current object is the object whose method is being called.


1 Answers

I think the following might be the reason.

Number is also a super-class of AtomicInteger and AtomicLong. If Number had an add() method these sub-classes would have had to implement it as well, which is impossible to do while preserving the atomicity.

Instead these two classes implement addAndGet() as a single atomic operation.

like image 120
PM 77-1 Avatar answered Nov 13 '22 18:11

PM 77-1