为什么我不能在同名的匿名类之外调用方法

编程入门 行业动态 更新时间:2024-10-23 19:21:37
本文介绍了为什么我不能在同名的匿名类之外调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

最后的代码产生编译错误:

The code at the end produces a compile error:

NotApplicable.java:7: run() in cannot be applied to (int) run(42); ^ 1 error

问题是为什么?为什么Javac认为我正在调用run(),却找不到run(int bar)?它正确地称为foo(int bar).为什么我必须使用NotApplicable.this.run(42);?是虫子吗?

The question is why? Why does javac think I am calling run(), and does not find run(int bar)? It correctly called foo(int bar). Why do I have to use NotApplicable.this.run(42);? Is it a bug?

public class NotApplicable { public NotApplicable() { new Runnable() { public void run() { foo(42); run(42); // uncomment below to fix //NotApplicable.this.run(42); } }; } private void run(int bar) { } public void foo(int bar) { } }

推荐答案

对代码示例行为的解释是,this被定义为您当前最里面"的类.在这种情况下,您是可运行子类的匿名内部类的最多"成员,并且没有与run(int)匹配的方法.要扩大搜索范围,请通过声明NotApplicable.this.run(42)指定要使用的this.

The explanation for the behavior of your code sample is that this is defined to be the class that you are currently "most" inside of. In this case, you are "most" inside the anonymous inner class that subclasses runnable and there is no method which matches run(int). To broaden your search you specify which this you want to use by stating NotApplicable.this.run(42).

jvm的评估如下:

this->当前正在使用方法run()

this -> currently executing instance of Runnable with method run()

NotApplicable.this->当前正在使用方法run(int)

NotApplicable.this -> currently executing instance of NotApplicable with method run(int)

编译器将在嵌套树中查找与该方法的NAME匹配的第一个方法. –感谢DJClayworth的澄清

The compiler will look up the nesting tree for the first method that matches the NAME of the method. –Thanks to DJClayworth for this clarification

匿名内部类不是外部类的子类.由于这种关系,内部类和外部类都应该具有一个具有完全相同签名的方法,而最内部的代码块应能够标识它要运行的方法.

The anonymous inner class is not a subclass of the outer class. Because of this relationship, both the inner class and the outer class should be able to have a method with exactly the same signature and the innermost code block should be able to identify which method it wants to run.

public class Outer{ public Outer() { new Runnable() { public void printit() { System.out.println( "Anonymous Inner" ); } public void run() { printit(); // prints "Anonymous Inner" this.printit(); //prints "Anonymous Inner" // would not be possible to execute next line without this behavior Outer.this.printit(); //prints "Outer" } }; } public void printit() { System.out.println( "Outer" ); } }

更多推荐

为什么我不能在同名的匿名类之外调用方法

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

发布评论

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

>www.elefans.com

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