开发者

question regarding the keyword super

In the book "Java in a Nutshell", chapter 3, section 3.5 Subc开发者_开发百科lasses and Inheritance, there is such as paragraph about the usage of super to access overriden method:

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.

What does it mean? There is no way for a instance of class C to call the f() of class A? Why?


It would break encapsulation. Suppose B.f() enforced some constraint - C.f() shouldn't be able to get around that by invoking A.f() directly. Instead, it has to go through B.f().


But there is no way for C.f() to invoke A.f( )

Yes, absoultely correct. You can only call the immediate superclass method.

Look at the Sun tutorial on super( )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜