【问题标题】:How to override a super class method [closed]如何覆盖超类方法[关闭]
【发布时间】:2018-07-07 01:42:59
【问题描述】:

大家好,我只是一个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"

【问题讨论】:

  • 不是。你没有把它分配给任何东西。

标签: java inheritance superclass


【解决方案1】:

你的代码没有任何意义:

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);
}

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

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

【讨论】:

  • 如果您还解释了他做错了什么并完成了您解决问题的选项,而不是只提供不会教 OP 他做错了什么的选项,您的答案会好得多。
  • @Jorge 好的。已编辑。
  • 现在很棒! +1
【解决方案2】:

这是我的猜测:

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();

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 2021-05-13
    • 1970-01-01
    • 2013-11-02
    相关资源
    最近更新 更多