实例的局部变量/方法的范围是什么 [英] What is the scope of the local variable/methods of an instance

查看:51
本文介绍了实例的局部变量/方法的范围是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试下面的代码段,我需要知道如何访问t.x或t.hello?它的范围是什么?开发人员是否以这种方式定义变量?

I am testing the snippet below, I need to know how can I access t.x or t.hello? What is its scope? Do developers define variables in this way?

public class Test{

public Test(){
    System.out.print("constructor\n");
}

public static void main(String[] args) {

    Test t = new Test(){
        int x = 0;
        //System.out.print("" + x);
        void hello(){
            System.out.print("inside hello\n");
        }
    };
}

修改

但是为什么这段代码有效

But why this snippet worked

 Thread  tr = new Thread() {
int loops = 1;

 @Override
 public void run() {
    loops += 1;
}
};
tr.start();

推荐答案

您应区分声明和定义.

在您的情况下,您声明一个类 Test 的变量,并将其分配给从 Test 派生的某个类的对象(这是一个匿名类),该对象具有一些其他功能在里面.

In your case you declare a variable of class Test and assign it to an object of some class derived from Test (it's an anonymous class) which has some additional stuff in it.

此定义之后的代码仅看到类 Test t ,而对 x hello 一无所知因为 Test 没有它们.

The code after this definition sees t of class Test only, it knows nothing about x and hello because Test doesn't have them.

因此,除了反射之外,在定义匿名类之后,不能使用 x hello .是的,开发人员在定义中需要这些变量时会使用此类变量.

So, apart from reflection, you cannot use x and hello after definition of an anonymous class. And yes, developers use such variables when they need these variables inside of definition.

有人提到您可以在定义后立即调用不属于 Test 的方法和访问变量:

It was mentioned that you can call methods and access variables that are not part of Test immediately after definition:

int y = new Test(){
    int x = 0;
    //System.out.print("" + x);
    void hello(){
        System.out.print("inside hello\n");
    }
}.x;

之所以可以这样做,是因为此时对象的类型是已知的(这是匿名类).一旦将此对象分配给 Test t ,就会丢失此信息.

This can be done because at this point the type of an object is know (it's the anonymous class). As soon as you assign this object to Test t, you lose this information.

这篇关于实例的局部变量/方法的范围是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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