因此,我设置了代码,以便将子类“ PBill”作为类“ customer”的继承扩展。但是,当我尝试在主函数中创建新的PBill对象时,它表示不存在此类对象,并且无法弄清楚该怎么做。这是我的示例:

public class customer {
private int reg;
private int prem;
private int raw;
private int total;
public customer(int re,int pr, int ra){
    this.reg=re;
    this.prem=pr;
    this.raw=ra;
    this.total=re+pr+ra;
}
public customer(int re){
    this(re,0,0);
}
public customer(int re,int pr){
    this(re,pr,0);
}
public int totalBag(){
    return(reg);
}
public double calctot(){
    if(this.reg>10){
        reg+=1;
    }
    double totcost=reg*10+prem*15+raw*25;
    return(totcost);
}
public String printBill(){
    return("You bought "+reg+" bags of regular food, "+prem+" bags of premium food, and "+raw+" bags of raw food. If you bought more than 10 bags of regular food, you get one free bag! Your total cost is: $"+this.calctot()+".");
}
class PBill extends customer{
public PBill(int re, int pr, int ra){
    super(re, pr, ra);
}
public PBill(int re, int pr){
    super(re,pr);
}
public PBill (int re){
    super(re);
}
public double calcTot(){
    return(super.calctot()*.88);
}
public String printPBill(){
    return("You are one of our valued Premium Customers! We appreciate your continued business. With your 12% discount, your total price is: $"+this.calcTot()+".");
}
}


当我尝试在具有主对象的另一个类中调用它来创建新对象时,会出现错误消息,如下所示:

public static void main(String[] args){
PBill c1=new PBill(10,2);


那是给我的错误是PBill无法解析为一种类型。

那么我将如何创建一个新的PBill对象,以便可以访问其中的方法,并且有一种更简单的方法来定义对象继承?

最佳答案

PBillcustomer的内部类,如果要实例化PBill的实例,可以将PBill的定义移出customer,请确保不要添加public
如果您不愿意这样做,仍然可以通过以下方式创建PBill实例:

customer c = new customer(1);
customer.PBill b = c.new PBill(1);

10-07 12:57