2017-08-15 69 views
-5

我正在学习Java中的多级继承,并且被困在下面的代码中。但它显示1错误。并且有没有其他方法可以做到这一点。我可以在使用方法时进行继承吗?任何人都可以提供帮助吗?提前。 这是错误:如何在下面的Java代码中删除多级继承中的错误?

shoppingmain.java:27:错误:类B中的构造方法B不能应用于给定的类型; { ^ 要求:字符串,整数

发现:没有参数

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

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(); 
    } 
    } 
+4

请:a)本减少到[MCVE] b)对代码进行格式化 - 目前全部都在这个地方; c)在问题中包含错误,而不是仅仅说“它显示错误”; d)按照Java命名约定使示例尽可能容易阅读; e)说出你想要达到的目标......你问“有没有其他的方式可以做到这一点”而不用说“这个”是什么。 –

+0

当你像@JonSkeet那样说,B扩展A可能是坏设计(重复变量是误解),并且打印方法也不好设计太 –

+0

除了@JonSkeet指出的内容,还请正确缩进代码;阅读“原样”非常具有挑战性。 – EJoshuaS

回答

0

正如你所宣布父类中的构造函数以及从父到孩子创建每个对象的继承工作,您需要指定参数来创建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); 
    } 
} 
0

我认为这是你正在尝试做的:

package javaapplication20; 

public class JavaApplication20 { 

    public static void main(String[] args)     
    { 
     B obj1 = new B("pen",5); 
     C obj2 = new C(2,10); 
     obj1.productdetails(); 
     obj2.productcost();   
    } 
} 

class A{ 
    int price; 
    String product; 
} 

class B extends A 
{ 
    int quantity; 
    int total; 

    B() { 

    } 

    B(int q, int t) { 
     quantity = q; 
     total = t; 
    } 

    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 h,int j) { 
     quantity = h; 
     total = j; 
    } 
    void productcost() 
    { 
     System.out.println("The quantity is "+quantity); 
     System.out.println("The total cost is "+total); 
    } 
} 
+0

编辑:这更接近您开始使用的内容。 – Charles