好的,我有一个作业,其中有一个抽象类“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;
}
}
我正在一步一步地确保一切正常,所以这是我迄今为止编写的唯一类(class)。我遇到的问题是当我测试类似
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
我不确定我在字符串中调用的“价格”和位置是否错误,或者我在尝试从抽象 Order 类实现这些方法时是否做错了什么
感谢您的帮助!
最佳答案
你的 super 构造函数没有设置位置
public Order(double price, String location){
}
所以这个构造函数
public NonProfitOrder(double price, String location) {
super(price, location); // calls super class' constructor
}
实际上并未设置价格
和位置
。
将 Order
的构造函数更改为
public Order(double price, String location){
this.double = double;
this.location = location;
}
未初始化的字段会被赋予默认值。对于引用类型,该值为 null
。对于数字类型,值为0
。对于 boolean 类型,值为 false
。这就是你所看到的。
关于java - 从抽象类扩展和打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18748890/