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

后端 未结 4 2163
心在旅途
心在旅途 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:27

    Your code creates an anonymous inner class. It's (more-or-less) equivalent to doing this:

    public class Test {
        // ...
        private class TestAnonymousInner extends Test {
            int x = 0;
            //System.out.print("" + x);
            void hello(){
                System.out.print("inside hello\n");
            }
        }
    
        public static void main(String[] args) {
            Test t = new TestAnonymousInner();
            // invalid:
            // t.hello(); 
        }
    }
    

    If you look at the compiler output for that file, you'll notice a file named something like Test$1.class – that's the anonymous class you've defined.

    Since the variable you're storing the instance in is of type Test, the fields aren't accessible through it. They're accessible through reflection, or from the constructor expression. E.g. the following works, although it's not particularly useful:

    new Test() {
        void hello() {
            System.out.println("hello()");
        }
    }.hello(); // should print "hello()"
    

    Re: your edit. start() is a method of Thread. The variable tr is also of type Thread, so you can call its methods. Just not methods you add in an AIC.

提交回复
热议问题