2014-04-19 48 views
0

所以我設置了代碼,使得我有一個子類'PBill'作爲類'customer'的繼承擴展。然而,當我嘗試在我的主函數中創建一個新的PBill對象時,它說沒有這樣的對象存在,並且它不知道該怎麼做。這是我的例子:擴展類(Java)的調用函數

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

這是它給出了:

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

當我嘗試將其與主要對象調用另一個類來創建一個新的對象,這樣會出現錯誤信息我是PBill無法解析爲類型的錯誤。

那麼我將如何去創建一個新的PBill對象,以便我可以訪問它裏面的方法,並且有沒有更簡單的方法來定義對象繼承?

+0

你在發生錯誤的行做什麼創建一個PBill實例,到底什麼是錯誤訊息? – laune

+0

這並沒有語義意義。賬單不是一種客戶,因此PBill不應該擴展客戶。 – Boann

回答

2

PBill是內部類的customer,如果你想要實例化的PBill一個實例,你可以移動的PBill定義出customer,一定不要加public
如果你不喜歡,你仍然可以通過

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

每個Java類應該在它自己的文件中,這是一樣的類名稱的名稱:customercustomer.javaPBillPBill.java

遵守約定:類名應以大寫字母(「Customer」)開頭。

使用繼承來鏈接相關的概念並不是最佳實踐。賬單是一個實體,而客戶是另一個實體。當然,可能有各種類型的客戶可以繼承。