在Java中混淆调用方法(Confusing calling method in Java)

系统教程 行业动态 更新时间:2024-06-14 16:59:47
在Java中混淆调用方法(Confusing calling method in Java) 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(); } }

我很迷惑为什么在调用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.

更多推荐

本文发布于:2023-04-17 09:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/614dac9e5fedbd19587020169659d2dd.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   Java   Confusing   method   calling

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!