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 Add sum = new Add();时,我解决了这个问题,
在同一个穆尔班。

为什么可以运行?为什么不能使用原始代码Mul sum = new Mul()

问题,我在Google中搜索过的总是说如何解决,但是我想知道这个概念。

拜托,这是我第一次用英语提问,如果您发现任何令人反感的内容,请原谅。

谢谢

最佳答案

Add.add方法返回类Add的对象。您试图将此对象的引用分配给类型为mul的变量Mul。这是不允许的,因为Add不是Mul的子类。 (实际上,MulAdd的子类,但这无关紧要。)

关于java - Java“不兼容类型”的原因?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19876130/

10-10 03:10