Search code examples
javaconstructorclass-design

Why am I getting this error "The constructor is undefined"?


In Java, getting this error:

Error: The constructor MyComplex(MyComplex) is undefined

Java Code:

public class MyComplex {
    int realPart, imaginaryPart;
    public MyComplex(){
    }
    public MyComplex(int realPart, int imaginaryPart) {
        this.realPart = realPart;
        this.imaginaryPart = imaginaryPart;
    }
    public void setRealPart(int realPart) {
        this.realPart = realPart;
    }
    public String toString() {
        return realPart + " + " + imaginaryPart +"i";
   }
}
public class MyComplexTester {
    public static void main(String[] args) {
        MyComplex a = new MyComplex(20, 50);
        MyComplex b = new MyComplex(a);        //Error happens here
        b.setRealPart(4);
        System.out.println(b);
    }
}

The code works fine if I use

MyComplex b = a;

But I can't change the code in the main method since its a homework on designing the class to run the given method.


Solution

  • Explanation

    You do not have a constructor that accepts another MyComplex (copy constructor). You only created constructors that accept:

    • No argument, new MyComplex()
    • Two int arguments, new MyComplex(5, 2)

    Solution

    You need to explicitly define constructors that you want to use. Java does not generate such a constructor for you. For example:

    public MyComplex(MyComplex other) {
        realPart = other.realPart;
        imaginaryPart = other.imaginaryPart;
    }
    

    Then it will also work.


    Notes

    In order to increase readability of your code, you should use explicit constructor forwarding for the new copy constructor and especially for your default constructor.

    As an example, right now your default constructor new MyComplex() will lead to a complex value of 0 + 0i. But this can easily be overseen since your code does not clearly indicate that.

    With forwarding, the intention is much clearer:

    public MyComplex() {
        this(0, 0);
    }
    
    public MyComplex(MyComplex other) {
        this(other.realPart, other.imaginaryPart);
    }
    

    Then both will just forward to the explicit constructor that accepts the two int values.

    Note that the only constructor Java auto-generates for you is the trivial default constructor. That is public MyComplex() { } (no arguments - does nothing). And only if you did not write any constructor yourself.