Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: add two values of the same type where both are subclasses of java.lang.Number

Tags:

java

I want to have a constructor like the following.

public Attribute(String attrName, Number attrValue){
    this.name = attrName;
    this.value = attrValue;
}

In this I would like to have a method called incrementValue(Number n) which will add n to value. I know you cannot add two Number objects together due to the possible issues with casting. However, if I use a check to guarantee value and n are the same type is it possible to add these together? Or perhaps there is a better way to go about this.

Right now I am declaring instance variables of Integer and Double and assign the value to the correct type. I was wondering about expanding this to allow for any subclass of Number. Obviously I could write separate methods for each one but that seems like bad programming.

Is this possible in java? Am I going about this completely wrong?

like image 207
thealfreds Avatar asked Apr 27 '12 02:04

thealfreds


1 Answers

You could convert all Numbers to a single type (double is least-lossy):

class Attribute {

    private double value;

    public Attribute(String attrName, Number attrValue) {
        this.name = attrName;
        this.value = attrValue.doubleValue();
    }

}

But IMO you're better off just overloading the constructor; Number is really just not a terribly useful class in my experience (and I don't seem to be the only one who thinks so).

class Attribute {

    public Attribute(String attrName, int attrValue) {
        this.name = attrName;
        this.value = attrValue;
    }

    public Attribute(String attrName, double attrValue) {
        this.name = attrName;
        this.value = attrValue;
    }
}
like image 109
Matt Ball Avatar answered Sep 25 '22 21:09

Matt Ball