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

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

    As written, neither x nor hello can be accessed outside the object referenced by t. The problem is that they are only declared in t's anonymous class. They are not defined in Test, and it is not possible to cast the t reference to the type in which they are declared, because it is anonymous.

    I have modified Test to make it abstract and add an abstract declaration of hello, allowing it to be called from outside the object referenced by t. I have also modified hello to add a use of x. Those changes illustrate the two ways of accessing anonymous class features - though the base class or internally.

    public abstract class Test {
    
      abstract void hello();
    
      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");
            System.out.print("My value of x is "+x);
          }
        };
        t.hello();
    
      }
    }
    

提交回复
热议问题