从抽象类扩展和打印

时间:2013-09-11 18:42:45

标签: java abstract-class extend

好的家伙我有一个带有抽象类'Order'的作业和另外三个扩展它'OverseasOrder','RegularOrder'和'NonProfitOrder'

的类

这是我的抽象类:

public abstract class Order {
    protected String location;
    protected double price;

  public Order(double price, String location){

  }

  public abstract double calculateBill();

  public String getLocation() {
    return location;
  }

  public double getPrice() {
    return price;
  }

  public abstract String printOrder(String format);

}

这是我的'NonProfitOrder':

public class NonProfitOrder extends Order {

public NonProfitOrder(double price, String location) {
    super(price, location);
}

public double calculateBill() {
    double bill;
    bill = price;
    return bill;
}

public String printOrder(String format){
    String Long = "Non-Profit Order" + "\nLocation: " + getLocation() +  "\nTotal Price: " + getPrice();
    return Long;
}

}

我正在逐步确保一切正常,所以这是我到目前为止所写的唯一课程。我遇到的问题是当我测试像

这样的东西时
public class OrderTester {

public static void main(String[] args) {
    Order o;
    o = new NonProfitOrder(2000.0, "NY");
    System.out.println(o.printOrder("Long"));
    }
}

非营利订单

位置:空

总价格:0.0

我不确定我是否在我的字符串中调用'price'和location'错误,或者我在尝试从抽象Order类实现这些方法时做错了什么

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

您的超级构造函数未设置位置

public Order(double price, String location){

}

所以这个构造函数

public NonProfitOrder(double price, String location) {
    super(price, location); // calls super class' constructor
}

实际上并未设置pricelocation

Order的构造函数更改为

public Order(double price, String location){
    this.double = double;
    this.location = location;
}

未初始化字段的默认值为。对于参考类型,该值为null。对于数字类型,值为0。对于布尔类型,值为false。这就是你所看到的。

答案 1 :(得分:0)

您刚刚错过了在抽象类中分配属性。

public Order(double price, String location){
    this.price = price;
    this.location = location;
}

public Order(double price, String location){ this.price = price; this.location = location; }

答案 2 :(得分:0)

您尚未初始化实例变量locationprice 所以Java provides default values for those
此处locationString类型对象,因此默认值为null
pricedouble类型,因此默认值为0.0

这些值在您的情况下打印为输出。 因此,尝试在Order类构造函数

中初始化它们
public Order(double price, String location){
    this.double = double;
    this.location = location;
}
相关问题