调用扩展类(Java)的函数

时间:2014-04-19 16:27:52

标签: java inheritance extends

所以我设置了代码,以便我有一个子类' PBill'作为一个班级客户的继承扩展'。但是,当我尝试在main函数中创建一个新的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对象,以便我可以访问其中的方法,是否有更简单的方法来定义对象继承?

2 个答案:

答案 0 :(得分:2)

PBillcustomer的内部类,如果要实例化PBill的实例,可以将PBill的定义移出customer },请务必不要添加public 如果您不喜欢这样,您仍然可以通过

创建PBill实例
customer c = new customer(1);
customer.PBill b = c.new PBill(1);

答案 1 :(得分:1)

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

遵守惯例:类名称应以大写字母开头(" Customer")。

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

相关问题