Use math operators for shared variables in a common Java class

I am trying to write code that will allow me to perform basic mathematical operations on an instance of the "T extends Number" object. It should be able to handle any type of number that is a subclass of Number .
I know that some of the types under Number have built-in .add() methods, and some even have .multiply() methods. I need to be able to multiply two common variables of any possible type. I searched and searched and could not find a clear answer.

 public class Circle<T extends Number> { private T center; private T radius; private T area; // constructor and other various mutator methods here.... /** The getArea method returns a Circle object area. @return The product of Pi time Radius squared. */ public Number getArea() { return 3.14 * (circle.getRadius()) * (circle.getRadius()); } 

Any help would be greatly appreciated. Generics are the hardest thing I've encountered while learning Java. I do not mind doing work on my feet, because I study better, so even a strong point in the right direction will be very useful.

+6
java generics math
source share
3 answers

What you need to do is use the double value of Number . However, this means that you cannot return the Number type.

 public double getArea() { return 3.14 * (circle.getRadius().doubleValue()) * (circle.getRadius().doubleValue()); } 
+4
source share

Java does not allow operators to be called in classes (therefore no +, -, *, /) you need to do the math as a primitive (I was going to show the code ... but jjnguy beat me before that :-).

+1
source share

You should check out http://code.google.com/p/generic-java-math/ , it solves the problem with general arithmetic in java and may even have the necessary geometric functions.

+1
source share

All Articles