trouble writing a static version of the add and subtract methods (this is in java)

215 views Asked by At

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;
}
}
2

There are 2 answers

4
Am_I_Helpful On BEST ANSWER

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 :-

@Override
public boolean equals(Complex firstNumber, Complex secondNumber) {
if (firstNumber.equals(secondNumber)) {
    return true;
} else {
    return false;
}

}
7
kevkev97kk On

Comparing Objects does not work. You need to compare the member variables within the Object. I believe that if you compare objects, all you are are comparing is the location the object is stored.

Next thing is...I don't think the realPart value and imaginaryPart value should be static. If you want each Complex Object to have a unique realPart and imaginaryPart value, it should just be a member variable.