What is the scope of the local variable/methods of an instance

后端 未结 4 2108
心在旅途
心在旅途 2021-01-21 14:56

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{         


        
4条回答
  •  隐瞒了意图╮
    2021-01-21 15:35

    You should distinguish declaration and definition.

    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.

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

    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.

    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;
    

    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.

提交回复
热议问题