JAVA 繼承的問題?

2017-05-23 6:24 pm
寫java繼承的時候遇到一些問題
以下是我的程式碼
class mylib {
public static void main(String[] args) {
Complex c3 = new myComplex(9,12);
c3=c3.sub(3);
System.out.print("c3.sub(3)="+c3);
}
}
class Complex {
private double real;
private double img;
public Complex(double r, double i) {
real=r;
img=i;
} public Complex(double r) {
real=r;
img=0;
} public String toString() {
if (img==0) {
return ""+real;
} else if (real==0) {
return img+"i";
} else if (img<0) {
return real+" - "+(-img)+"i";
} else {
return real+" + "+img+"i";
}
}public void print() {
System.out.print(toString()); }
public double getReal() { return real; }
public double getImg() { return img; }
public Complex sub(Complex c) {
return new Complex(real-c.getReal(),img-c.getImg()); } }

class myComplex extends Complex {

public myComplex(double r, double i) {
super(r,i);
}
public myComplex(Complex c) {
super(c.getReal(),c.getImg());
}
public myComplex sub(myComplex c) {
return new myComplex(super.sub(c));
}
public myComplex sub(double r) {
Complex c = sub(new Complex(r));
myComplex c3 = new myComplex(c.getReal(),c.getImg());
return c3;
}
}
編譯完後會出現
error: incompatible types: int cannot be converted to Complex
c3=c3.sub(3);
^
如果程式只能改myComplex的部份
要怎麼改才會成功
請高手來幫我解答
更新1:

Complex c3 = new myComplex(9,12); 這行跟Complex都不能動哦 所以我才會卡在這裡...不知道要怎麼改

回答 (1)

2017-05-24 9:15 am
這行能動嗎?
Complex c3 = new myComplex(9,12);

myComplex c3 = new myComplex(9,12);

更:
那這行呢?
c3=c3.sub(3);

c3=c3.sub(new Complex(3));


收錄日期: 2021-05-04 02:23:17
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20170523102453AA84Syt

檢視 Wayback Machine 備份