I have this interface:
public interface Numeric {
public Numeric addition(Numeric x,Numeric y);
public Numeric subtraction(Numeric x,Numeric y);
}
And this class:
public class Complex implements Numeric {
private int real;
private int img;
public Complex(int real, int img) {
this.real = real;
this.img = img;
}
public Numeric addition(Numeric x, Numeric y) {
if (x instanceof Complex && y instanceof Complex) {
Complex n1 = (Complex)x;
Complex n2 = (Complex)y;
return new Complex(n1.getReal() + n1.getReal(), n2.getImg() +
n2.getImg());
}
throw new UnsupportedOperationException();
}
public Numeric subtraction(Numeric x, Numeric y) {
if (x instanceof Complex && y instanceof Complex) {
Complex n1 = (Complex)x;
Complex n2 = (Complex)y;
return new Complex(n1.getReal() - n1.getReal(), n2.getImg() -
n2.getImg());
}
throw new UnsupportedOperationException();
}
public int getReal() {
return real;
}
public int getImg() {
return img;
}
}
Why do I get this error:
incompatible types: Numeric cannot be converted to Complex
when I run this code:
public class TestNumeric {
public static void main(String[] args) {
Complex c1 = new Complex(3, 4);
Complex c2 = new Complex(1, 2);
Complex rez;
rez = rez.addition(c1, c2);
}
}
The error is at the line "rez = rez.addition(c1, c2);"
Complex implements Numeric, so every Numeric is a Complex, right? I have already done casting and checking inside the addition method. Why do I get this error, and how can I fix it?