调用超类方法在覆盖后只能通过受保护的访问方式进行,不传递参数。

huangapple go评论69阅读模式
英文:

Calling super method after over-riding only possible by protected access without argument passing

问题

尝试理解Java面向对象编程(主要是Python编程者)。我无法在重写中从子类调用父类方法。
示例:
从子类支票账户(Checking account),我尝试重写父类方法,然后如果失败了调用super.method。

public String allowWithdraw(Integer amount) {
    if (amount < this.withdrawalLimit) {
        return "Yes";
    } else {
        return super.allowWithdraw(amount);
    }
}

父类银行账户(Banking account)有allowWithdraw方法。

public String allowWithdraw(Integer amount) {
    return "No, calling super";
}

这会导致语法错误建议的失败。如果我除了原始方法之外还有受保护的访问包方法,并且只有没有传递任何参数,该方法会被调用。我在这里查阅了资源,但无法弄清楚原因。

protected String allowWithdraw(Integer amount) {
    return "No, calling super";
}
英文:

Trying to understand Java OOP (Python coder predominantly). I wasn't able to call parent class method from child class in the over-ride.
Example:
From Child class Checking account, I'm trying to over-ride parent method, and then if fails call super.method.

public String allowWithdraw(Integer amount) {
    if (amount &lt; this.withdrawalLimit) {
        return &quot;Yes&quot;;
    } else {
        return super.allowWithdraw(Integer amount);
    }
}

Parent class Banking account has allowWithdraw method.

public String allowWithdraw(Integer amount) {
    return &quot;No, calling super&quot;;
}

This fails showing syntax error suggestions. If I have protected access package method additionally to the original one, the method gets called. And, only if there isn't any argument passing. I went through resources here, and I'm not able to figure out why.

protected String allowWithdraw(Integer amount) {
    return &quot;No, calling super&quot;;
}

答案1

得分: 1

你有

return super.allowWithdraw(amount);

在这里删除 Integer。你只需要在声明函数时指定数据类型,而不是在调用函数时指定。

英文:

You have

return super.allowWithdraw(Integer amount);

Remove Integer here. You only specify the data type when you declare the function, not when you call it.

huangapple
  • 本文由 发表于 2020年9月24日 06:18:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64037031.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定