为什么我不能在同名的匿名类之外调用方法 [英] Why can't I call a method outside of an anonymous class of the same name

查看:126
本文介绍了为什么我不能在同名的匿名类之外调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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" );
    }
}

这篇关于为什么我不能在同名的匿名类之外调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆