我有这个界面:
public interface Numeric
{
public Numeric addition(Numeric x,Numeric y);
public Numeric subtraction(Numeric x,Numeric y);
}
这堂课
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;
}
}
为什么会出现此错误:
不兼容的类型:数字不能转换为复杂的
当我运行这段代码时:
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);
}
}
错误在“ rez = rez.addition(c1,c2);”行中
复合体实现数字,因此每个数字都是复合体,对吗?我已经在附加方法中进行了转换和检查。为什么会出现此错误,该如何解决?
答案 0 :(得分:-2)
addition
和subtraction
的声明是错误的。应该如下:
public interface Numeric {
public Numeric addition(Numeric obj);
public Numeric subtraction(Numeric obj);
}
,然后您对addition
和subtraction
的实现应如下:
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();
}
}
最后,TestNumeric
应该如下:
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);
}
}
更新:
@OrosTom-根据您的评论,我添加了需要放入类Complex
中的方法,以便您可以打印结果
@Override
public String toString() {
return real + " + " + img + "i";
}
此后,输出以下代码
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);
}
}
将是
3 + 4i
1 + 2i
4 + 6i