簡體   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