gpt4 book ai didi

java - 关于关键字 super 的问题

转载 作者:行者123 更新时间:2023-12-02 14:06:04 24 4
gpt4 key购买 nike

在《Java in a Nutshell》一书中,第3章,第3.5节子类和继承,有这样一段关于使用super来访问重写方法的段落:

Note that the super keyword invokes the most immediately overridden version of a method. Suppose class A has a subclass B that has a subclass C and that all three classes define the same method f( ). The method C.f() can invoke the method B.f( ), which it overrides directly, with super.f( ). But there is no way for C.f() to invoke A.f( ) directly: super.super.f( ) is not legal Java syntax. Of course, if C.f() invokes B.f( ), it is reasonable to suppose that B.f( ) might also invoke A.f(). This kind of chaining is relatively common when working with overridden methods: it is a way of augmenting the behavior of a method without replacing the method entirely. We saw this technique in the the example finalize() method shown earlier in the chapter: that method invoked super.finalize() to run its superclass finalization method.

这是什么意思? C类的实例没有办法调用A类的f()吗?为什么?

最佳答案

这会破坏封装。假设 B.f() 强制执行了一些约束 - C.f() 不应该能够通过直接调用 A.f() 来绕过该约束。相反,它必须通过B.f()

关于java - 关于关键字 super 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6095280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com