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?
The declaration of addition
and subtraction
should be as follows:
public interface Numeric {
public Numeric addition(Numeric obj);
public Numeric subtraction(Numeric obj);
}
and the implementation of addition
and subtraction
should be as follows:
public Numeric addition(Numeric obj){
if (obj instanceof Complex){
Complex n = (Complex)obj;
return new Complex(this.getReal() + n.getReal(), this.getImg() +
n.getImg());
} else {
throw new UnsupportedOperationException();
}
}
Finally, TestNumeric
should be as follows:
public class TestNumeric {
public static void main(String[] args) {
Numeric c1 = new Complex(3, 4);
Numeric c2 = new Complex(1, 2);
Numeric rez = c1.addition(c2);
}
}
[Update]
@OrosTom - Based on your comment, I have added below the method that you need to put inside the class, Complex
so that you can print the result
@Override
public String toString() {
return real + " + " + img + "i";
}
Note: please check https://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html (section, The toString() Method) for more details.
After this, the output of the following code
public class TestNumeric {
public static void main(String[] args) {
Numeric c1 = new Complex(3, 4);
Numeric c2 = new Complex(1, 2);
Numeric rez = c1.addition(c2);
System.out.println(c1);
System.out.println(c2);
System.out.println(rez);
}
}
will be:
3 + 4i
1 + 2i
4 + 6i