我很迷惑为什么在调用method1()时会在Parent :: method2()中调用Parents method1()而不是Childs method1? 我发现只有当method1()是私有的时候才会发生这种情况。 有人可以解释我为什么吗? 谢谢。
class Parent { private void method1() { System.out.println("Parent's method1()"); } public void method2() { System.out.println("Parent's method2()"); method1(); } } class Child extends Parent { public void method1() { System.out.println("Child's method1()"); } } class test { public static void main(String args[]) { Parent p = new Child(); p.method2(); } }I'm confuse why does in Parent::method2() when invoking method1() it will cal Parents method1() and not Childs method1 ? I see that this happens only when method1() is private? Can someone explain me why ? Thanks you.
最满意答案
这发生在范围规则的基础上; 在Parent中, method1的最佳匹配是类本地私有版本。
如果要将method1定义为public或Parent protected并在Child重写该方法,则调用method2将调用Child的method1 。
This happens based on scoping rules; in Parent the best match for method1 is the class-local private version.
If you were to define method1 as public or protected in Parent and override the method in Child, then calling method2 would invoke Child's method1 instead.
更多推荐
发布评论