I need help writing a static version of the add and subtract methods. i have tried to do so but im not really sure if this is the right way and also my equals method is not working . When i compile my equals method it always prints false.
public static void main(String[] args) {
Complex c1 = new Complex(7, 7);
Complex c2 = new Complex(7, 7);
System.out.println(Complex.add(c1, c2));
System.out.println(c1.equals(c2));
}
}
class Complex {
private static double realPart;
private static double imaginaryPart;
public Complex() {
realPart = 0;
imaginaryPart = 0;
}
public Complex(double c1, double c2) {
realPart = c1;
imaginaryPart = c2;
}
public static Complex add(Complex firstNumber, Complex secondNumber) {
Complex result = new Complex();
firstNumber.realPart = 7;
secondNumber.imaginaryPart = 7;
result.realPart = firstNumber.realPart + secondNumber.imaginaryPart;
return result;
}
public static Complex subtract(Complex firstNumber, Complex secondNumber) {
Complex result = new Complex();
firstNumber.realPart = 7;
secondNumber.imaginaryPart = 7;
result.realPart = firstNumber.realPart + secondNumber.imaginaryPart;
return result;
}
public boolean equals(Complex firstNumber, Complex secondNumber) {
if (firstNumber == secondNumber) {
return true;
} else {
return false;
}
}
public String toString() {
return "result= " + realPart;
}
}
Objects are always compared using
equals()
method.==
isn't the way to compare Objects!!!(THIS HAS BEEN POSTED ABOUT HUNDREDS OF TIMES OR MORE ON STACK OVERFLOW FORUM)
Also,add an
@Override
annotation to be more clear so that you're overriding the equals method...Improve your code as :-