difference between declaring an object on class le

2019-08-12 02:07发布

问题:

A is another class outside of test

case 1:

public class Test{



      A testObj;

      public static void main(String[] args){
         testObj=new A();
         testObj.methodInsideClassA();
      }
}

case 2:

 public class Test{


      public static void main(String[]  args){
         A testObj = new A();
         testObj.methodInsideClassA();
      }
}

so whats the difference between them? And what should I use?

回答1:

Case 1

testObj is a class-level variable.

Case 2

testObj is a local variable. A local variable is the one that is declared within a method or a constructor.

One important distinction between class-level variable and local variable is that access specifiers can be applied to class-level variables only and not to local variables.



回答2:

If this object should be shared between some method runs, you should use the first options. In other cases (temporary object), you should use the second.



回答3:

The difference between of the two declaration in the scope of the instance/object of A.

In first case the testObj is accessible from the all method of class Test In second case the testObj is accessible only from the main() method of class Test. While main() method terminated testObj also removed from the memory.

What you have to use it depends on situation. Suppose in some case you require the instance of A (that is testObj ) in all over of your Test class - means several methods of class Test uses the same instance of A. Then you declare testObj outside of all methods of class Test - that is as an instance variable.

When different method of class Test requires different instance of A then you may use method local variable as in case 2.