Below is selected code from one of 5 classes for this assignment.
Each class must have a equals() method that can compare an object of its class to an object of any and all of the 5 classes.
My strategy is to convert each object value to a double for the sake of precision.
As each Class extends Number each class has a doubleValue() method to utilize.
the code would not compile unless I typecasted x to RationalN before executing doubleValue()
but when executing the code it complains when a object of another class is compared as it can’t be typecasted to that Class.
I where do I go from here?
public class RationalN extends Number{
private int numerator;
private int denominator;
public RationalN(int x, int y){
if (y == 0){
throw new ArithmeticException("cannot devide by zero");
} else {
this.numerator=x;
this.denominator=y;
}
}
public double doubleValue(){
double value = (double)numerator/(double)denominator;
return (double)value;
}
public boolean equals(Object x){
if (((RationalN)x).doubleValue() == this.doubleValue()){
return true;
} else {
return false;
}
}
From what I get from your post, you want to check in equals whether the numeric value represented by your object equals the numeric value of the argument object. Therefore, comparing the classes is not appropriate. Instead, your equals() method has too look something like this:
This, however, violates the equals() contract:
new RationalN(1, 1).equals(new Integer(1)) would return true, but new Integer(1).equals(new RationalN(1, 1)); wouldn’t – the above equals() method violates symmetry. It would therefore be appropriate to introduce an abstract class implementing Number (say, MyNumber) which is extended only by your five classes and implements equals() in the above fashion (using instanceof MyNumber).