0

I created a class Complex to do Complex operators. Inside the Complex class I made a method add which uses two Complex class parameters. But when I create two instances in main() and then try to add them.

public class ComplexNo {
    public static void main(String[] args){
        Complex c1=new Complex(1,1);
        Complex c2=new Complex(2,3);
        Complex cAdd=Complex.add(c1,c2);
    }
}
class Complex{
    float real; float imag;
    Complex(float a, float b){
        real = a;
        imag = b;
    }
    Complex add(Complex a, Complex b){
        return new Complex(a.real+b.real, a.imag+b.imag);
    }
}

It shows the error "Non-static method 'add(Complex, Complex)' cannot be referenced from a static context". It is corrected by adding static keyword. How does it help?

  • Does this answer your question? [Non-static variable cannot be referenced from a static context](https://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context) – Turing85 Jul 21 '23 at 14:28
  • 1
    `Complex cAdd=Complex.add(c1,c2);` <- this is simply not how you call instance methods on objects. I strongly recommend going back and reading a basic tutorial about how instance methods are called in java: https://docs.oracle.com/javase/tutorial/java/javaOO/usingobject.html and also reading up about [what static means in java](https://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class) – OH GOD SPIDERS Jul 21 '23 at 14:29
  • 1
    You are mixing two options. Either declare `static Complex add(Complex c1, Complex c2)` or `Complex add(Complex other)`. – Jorn Jul 21 '23 at 14:29
  • Add `static` to your `add` method: `static Complex add(Complex a, Complex b) { ...` – OscarRyz Jul 21 '23 at 14:35
  • 1
    When making a method that takes 2 complex, you don't need the 'context' of a complex number. This isn't OO and isn't proper java style. What would be much better is `public Complex plus(Complex other) { return new Complex(this.real + other.real, this.imag + other.imag); }` - instead of "A function that is given 2 complex numbers that makes a new one", you now have: "A function you can call _on an instance of Complex_, you pass another instance of Complex, and as a result the instance of Complex adds the other number to itself and returns that. – rzwitserloot Jul 21 '23 at 14:46

0 Answers0