繁体   English   中英

扩展类的调用函数(Java)

[英]Calling function of an Extended Class (Java)

因此,我设置了代码,以便将子类“ 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可以将PBill的定义移出customer ,请确保不要添加public
如果您不喜欢这样做,仍然可以通过以下方式创建PBill实例:

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

每个Java类都应位于其自己的文件中,该文件名应与类名相同: customer上的customer.javaPBill上的PBill.java

遵守约定:类名应以大写字母(“客户”)开头。

使用继承来链接不相关的概念不是最佳实践。 账单是一个实体,客户是另一个。 当然,可能存在适用继承的各种类别的客户。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM