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?
You could convert all Number
s 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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With