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

I want to have a constructor as shown below.

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) that will add n to the value. I know that you cannot add two Number objects together due to possible casting problems. However, if I use validation to guarantee the value, and n is the same type, can they be combined together? Or maybe there is a better way to do this.

Now I declare Integer and Double instance variables and assign the value to the correct type. I was interested in expanding this to allow any subclass of Number. Obviously, I could write separate methods for each, but this seems like poor programming.

Is this possible in java? Do I really disagree about this?

+5
source share
2 answers

You can convert everything Numberto one type ( doubleis the least unprofitable):

class Attribute {

    private double value;

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

}

But IMO, you better just overload the constructor; Numberreally just not a very useful class in my experience (and I, it seems, is not 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;
    }
}
+5
source

No, this is not possible in Java. The best you can do is go through all the cases Numberthat you know about.

I could, of course, write a subclass Numberfor which this was not possible, although this would be a slightly meaningless implementation.

0
source

All Articles