Force invocation of base class method

后端 未结 6 421
庸人自扰
庸人自扰 2020-12-11 23:53

The following code when run obviously prints out \"B1/A2/B2\". Now, is it possible for it to print \"A1/A2/B2\" instead (i.e. A#method2() should invoke method1() on A, not

6条回答
  •  隐瞒了意图╮
    2020-12-12 00:49

    Using standard "natural" and well accepted Java mechanisms you cannot. Java is designed so that all methods are dynamically dispatched unless final or static (or called to super), and in your case. Since the method is overridden in B, none of these is an option. There is no mechanism to "disable" dynamic dispatching in specific cases but the good news is that there is rarely a need to.

    You could overcome some of these limitations with reflection, but that's like unwrapping a precious gift with sledgehammer.

提交回复
热议问题