Scope of static variable and methods in Java

后端 未结 6 1279
自闭症患者
自闭症患者 2021-01-18 21:38

I have some doubts about usage of static method in Java. I read many places static variables are instance independent so be comes global.

public class ThirdC         


        
6条回答
  •  一向
    一向 (楼主)
    2021-01-18 22:03

    @eternal I think I am getting the point you wanna ask. I tested this (with some minor compile changes) on Jboss. The results were: Once deployed the scope of class ThirdClass seems to be application deployment level. And the static value of var was retained while multiple method calls.

    Here is the basic structure i used.

    public class ThirdClass {
    public static var = "Java";
    }
    
    public class Second class{
    
      public  void testA {
      ThirdClass ob1 = new ThirdClass();    // not needed , just kept for clarity.
      System.out.println(ThirdClass.var);   
      ThirdClass.var="Ruby";
      ThirdClass ob2 = new ThirdClass();        
      System.out.println(ThirdClass.var);  
    } 
    
     public class First {
    
      public  void testB {
      ThirdClass ob3 = new ThirdClass(); 
      System.out.println(ThirdClass.var); 
       ThirdClass.var="CSHARP";
    
     }
    
     public  void testC {
     ThirdClass ob4 = new ThirdClass(); 
     System.out.println(ThirdClass.var);        
    
    } 
    

    By webservices calls ( i have a setup) called these methods in secquence testA() --> Display var = "Ruby"

    testB() --> Display var = "Ruby"

    testC() --> Display var ="CSHARP"

    So the new changed values were shared by DIFFERENT METHOD CALLS throught application deployment. So scope of ThirdClass was deployment level.

提交回复
热议问题