如何在对super的调用中简化该数学运算?

时间:2019-02-07 22:37:58

标签: java oop inheritance super

我正在尝试做一个模拟杂货店的项目,该杂货店出售各种甜点。当前,我正在尝试为分层蛋糕创建一个类,该类是从蛋糕类派生而来的,而蛋糕类本身又是抽象甜点类的派生。本质上,cake类的构造函数具有两个参数,名称和价格。对于分层蛋糕,价格为基础价格+顶层价格+总额的10%。我找到了一种方法来执行此操作,但是这是很长很丑陋的代码行。我已经尝试了几种尝试使用变量来简化它的方法,但是似乎无法找出一种可以在super()中完成的事实。有没有办法使我更简单,更有效?预先感谢!

代码如下:

public class TieredCake extends Cake {
    private Cake base;
    private Cake top;

    public TieredCake (Cake base, Cake top) {
        super(base.getName() + " with an upper tier of " + top.getName(), (base.getPrice() + top.getPrice()) * 0.10 + base.getPrice()+top.getPrice());
        this.base = base;
        this.top = top;
    }

    public Cake getBase() {
        return base;
    }

    public Cake getTop() {
        return top;
    }
}

1 个答案:

答案 0 :(得分:2)

将对super的呼叫分成多行会有所帮助:

public TieredCake(Cake base, Cake top) {
    super(
        base.getName() + " with an upper tier of " + top.getName(),
        (base.getPrice() + top.getPrice()) * 0.10 + base.getPrice() + top.getPrice()
    );

    this.base = base;
    this.top = top;
}

但更重要的是,让我们看一下该公式。我们可以在数学上做一些简化:

B := base.getPrice()
T := top.getPrice()

(B + T) * 0.1 + B + T
= (B * 0.1) + (T * 0.1) + B + T
= (B * 1.1) + (T * 1.1)
= (B + T) * 1.1

这给了我们

public TieredCake(Cake base, Cake top) {
    super(
        base.getName() + " with an upper tier of " + top.getName(),
        (base.getPrice() + top.getPrice()) * 1.1
    );

    this.base = base;
    this.top = top;
}