如何在以下Java代码中删除多级继承中的错误?

时间:2017-08-15 15:07:33

标签: java

我正在学习Java中的多级继承,我陷入了下面的代码。但是它显示了1个错误。还有其他方法可以做到这一点。我可以在使用方法时继承吗?有人可以帮忙吗?谢谢提前。 这是错误:

shoppingmain.java:27:错误:B类中的构造函数B不能应用于给定的类型; { ^   required:String,int

发现:没有参数

原因:实际和正式的参数列表长度不同

1错误

    class A{
    int price;
    String product;
    }

    class B extends A
    {
     int quantity; 
     int total;
    B(String a,int b)
    {

    product=a;
    price=b;
    }
    void productdetails()
    {
     System.out.println("The product name is"+product);
     System.out.println("The price is"+price);
    }
    }

    class C extends B
    {
    C(int c,int d)
    {          //line 27
    quantity=c;
    total=d;
    }
    void productcost()
    {
    System.out.println("The quantity is"+quantity);
    System.out.println("The total cost is"+total);
    }
    }

    class shoppingmain
    {
    public static void main(String args[])
    {

    B obj1=new B("pen",5);
    C obj2=new C(2,10);

    obj1.productdetails();
    obj2.productcost();
    }
    }

2 个答案:

答案 0 :(得分:0)

正如你在父类中声明了一个构造函数,并且继承可以创建从父对象到子对象的每个对象,你需要使用 super 来指定创建B对象的参数C中的关键字:

public class C extends B
{
    C(int c, int d)
    {
        super("Prueba", 1);
        quantity = c;
        total = d;
    }

    void productcost()
    {
        System.out.println("The quantity is" + quantity);
        System.out.println("The total cost is" + total);
    }
}

答案 1 :(得分:0)

我认为这就是你要做的事情:

[alias]
    st = status