views:

37

answers:

2

specificly im trying to write a piece of code that will allow me to perform basic math operations on a "T extends Number" object variable. it needs to be able to handle any number type that is a subclass of Number.
i know some of the types under Number have .add() methods built in, and some even have .multiply() methods built in. i need to be able to multiply two generic variables of any possible type. i've searched and searched and haven't been able to come up w/ a clear answer of any kind.

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's area.
  @return The product of Pi time Radius squared.
*/

public Number getArea()
{
    return  3.14 * (circle.getRadius()) * (circle.getRadius());      
}  

any help would be much appreciated. generics are the most difficult thing i've encountered in learning java. i don't mind doin the leg work cause i learn it better that way. so even a strong point in the right direction would be very helpful.

Thanks,
-Will-

+2  A: 

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

public double getArea()
{
    return  3.14 * 
            (circle.getRadius().doubleValue()) * 
            (circle.getRadius().doubleValue());      
}  
jjnguy
A: 

Java does not allow operators to be called on classes (so no +, -, *, /) you have to do the math as a primitive (I was going to show the code... but jjnguy beat me to it :-).

TofuBeer