如何覆盖超类方法

时间:2018-01-28 03:56:55

标签: java inheritance superclass

大家好我只是java的初学者,我想覆盖这样的超类方法:

public class ShippedOrder extends Order{
    private final int ship = 15;

    public ShippedOrder(String cusName, int cusNo, int qty, double unitPrice, int ship){
        super(cusName, cusNo, qty, unitPrice);
    }

    public void setShip(int ship){
        super.computePrice() + ship;
    }
}

但是消息显示"+ is not a statement"

2 个答案:

答案 0 :(得分:2)

您的代码没有任何意义:

public void setShip(int ship){
        super.computePrice() + ship;
}

super.computePrice()是一个返回内容或返回void的函数。您正在为其添加int,但您没有对其进行任何操作。假设此函数返回100.0。然后它等同于行100.0 + 15;这不是Java中的语句。

我假设您希望ShippedOrderOrder的价格增加ship。如果是这样,我建议删除setShip函数,并在调用Order的构造函数时传递unitPrice + ship

public ShippedOrder(String cusName, int cusNo, int qty, double unitPrice, int ship){
    super(cusName, cusNo, qty, unitPrice+ship);
}

如果您不想这样做,请考虑在shipPrice中保留值ShippedOrder并在构造函数中设置它。

public ShippedOrder(String cusName, int cusNo, int qty, double unitPrice, int ship){
    super(cusName, cusNo, qty, unitPrice);
    this.shipPrice = ship;
}

答案 1 :(得分:0)

这是我的猜测:

Order类(父类)中,它具有computePrice()方法。我认为它是一个计算&退货价格:

// Assume in your "Order" class, you have:
public double computePrice() {
    // whatever calculation here ....
    double price = this.qty * this.unitPrice;

    return price;
}

然后现在你有ShippedOrder类,它扩展了Order类。您添加了ship作为新成员变量。如果您想将ship值添加到computePrice()返回的价格,您可以尝试这样做:

public class ShippedOrder extends Order {
    // this is declared final, so it's value can only be set once in constructor
    // I would just declare it as double just to follow unitPrice type.
    private final double ship;

    public ShippedOrder (String cusName, int cusNo, int qty, double unitPrice, double ship) {
        super(cusName, cusNo, qty, unitPrice);

        // assign value pass in to member variable
        this.ship = ship;
    }

    @Override
    public double computePrice() {
        return super.computePrice() + this.ship;
    }
}

然后这样打电话:

ShippedOrder shippedOrder = new ShippedOrder("MyName", 100, 2, 200.5, 15);
double price = shippedOrder.computePrice();

希望这有帮助,祝你好运!