变量r可能尚未初始化 [英] variable r might not have been initialized

查看:112
本文介绍了变量r可能尚未初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个非常简单的程序:

There's a very simple program:

public class A {
    public static void main(String[] p) {
        final Runnable r = new Runnable() {
            public void run() {
                System.out.println(r);
            }
        };
        r.run();
    }
}

这给出了:

$ javac A.java 
A.java:6: variable r might not have been initialized
                System.out.println(r);
                                   ^
1 error

  1. 为什么?
  2. Runnable如何引用指向它的变量?

(在实际代码中,还有一个级别(一个侦听器),并且通过this进行引用不起作用)

(In the real code, there is one more level (a listener), and referencing via this does not work)

推荐答案

在这种情况下,可以使用"this"来避免编译错误:

In this case, you can use "this" to avoid the compilation error:

    final Runnable r = new Runnable() {
        public void run() {
            System.out.println(this); // Avoid compilation error by using this
        }
    };

这篇关于变量r可能尚未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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