[英]Incompatible types error Java between short and int. Unsure of cause
[英]The cause of java “incompatible types”?
import java.util.*;
class Poly{
protected int[] coef = new int[1001];
protected int[] exp = new int[1001];
protected int len;
protected void attach(int c, int e){
coef[len] = c;
exp[len++] = e;
}
protected void print() {
for (int i=0; i<len; i++)
System.out.print(coef[i]+" "+exp[i]+" ");
System.out.println();
}
}
class Add extends Poly{
protected Add add(Add y) {
int i,j;
Add rel = new Add();
for(i=0, j=0; i<len && j<y.len;) {
if(exp[i] < y.exp[j]) {
rel.attach(y.coef[j], y.exp[j]);
j++;
} else if(exp[i] > y.exp[j]) {
rel.attach(coef[i], exp[i]);
i++;
} else{
int c = coef[i] + y.coef[j];
if(c != 0)
rel.attach(c,exp[i]);
i++;
j++;
}
}
while(i < len)
rel.attach(coef[i], exp[i++]);
while (j < y.len)
rel.attach(y.coef[j], y.exp[j++]);
return rel;
}
}
class Mul extends Add{
protected Add mul(Add y){
Mul sum = new Mul(); //the following error has been solved by change this
//Mul to Add , why?
for(int i=0;i<len;i++){
Mul tmp = new Mul();
for(int j=0; j<y.len; j++)
tmp.attach(coef[i]*y.coef[j], exp[i]+y.exp[j]);
sum = sum.add(tmp); //there are an error here
//incompatible types
//required : Mul
//found : Add
}
return sum;
}
}
public class answer{
public static void main(String[] argv){
Mul d = new Mul();
Mul e = new Mul();
d.attach(6,4);
d.attach(7,2);
d.attach(2,1);
d.attach(8,0);
e.attach(9,5);
e.attach(3,2);
e.attach(-1,1);
e.attach(5,0);
System.out.println("Mul");
System.out.println("D(x)= 9 5 3 2 -1 1 5 0");
System.out.println("E(x)= 6 4 7 2 2 1 8 0");
System.out.print("F(x)=");
d.mul(e).print();
}
}
這是一個簡單的BigInt
示例,我練習了我的擴展概念,
類Mul中有錯誤:
sum = sum.add(tmp);
^
incompatible types
required : Mul
found : Add
當我改變Mul sum = new Mul(); to
時,我解決了這個問題Mul sum = new Mul(); to
Mul sum = new Mul(); to
添加總和=新添加();`,在相同的Mul的類。
它為什么能運行? 為什么我不能使用原始代碼Mul sum = new Mul()
?
問題,我在谷歌搜索總是說如何解決,但我想知道這個概念。
拜托,這是我第一次用英語提問,如果你發現任何令人反感的話,請原諒。
謝謝
問題是add
方法被聲明為返回Add
- 但是你試圖將返回值賦給Mul
類型的變量。 那是無效的。 如果您將聲明的sum
類型更改為Add
而不是mul
,那么即使您使用類型為Mul
的值初始化sum
,該分配仍然可以。
如果將方法調用從賦值中分離回sum
,則可能會更清楚:
Mul sum = new Mul();
Mul tmp = new Mul();
...
Add result = sum.add(tmp);
sum = result; // This is the bit that's invalid
它真不明白你想要在這里實現什么,但我很懷疑一個的Mul
擴展類Add
到開始...
Add.add
方法返回Add
類的對象。 您正嘗試將此對象的引用分配給具有Mul
類型的變量mul
。 這是不允許的,因為Add
不是Mul
的子類。 (事實上, Mul
是Add
的子類,但那是無關緊要的。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.