Can non-static methods modify static variables

前端 未结 9 2078
猫巷女王i
猫巷女王i 2020-11-29 01:53

I am wondering how a non static method can modify a static variable. I know that static methods can only access other static methods and static variables. However, is the ot

9条回答
  •  [愿得一人]
    2020-11-29 02:08

    Non-Static Methods can access both Static Variables & Static Methods as they Members of Class

    Demo Code

    public class Static_Class {
        protected static String str;
        private static int runningLoop;
    
        static{
            str = "Static Block";
        }
    
        /**
         * Non-Static Method Accessing Static Member  
         */
        public void modifyStaticMember(){
            str = "Non-Static Method";      
        }
    
        /**
         * Non-Static Method invoking Static Method
         */
        public void invokeStaticMethod(){
            String[] args = {};
            if(runningLoop == 0){
                runningLoop++;
                main(args); 
            }
            //Exiting as it will lead to java.lang.StackOverflowError
            System.exit(0);
        }
    
        public static void main(String[] args) {
            Static_Class instance = new Static_Class();
            System.out.println(str);
            instance.modifyStaticMember();
    
            // Changed Value persists 
            System.out.println(str);
    
            //Invoking Static Method
            instance.invokeStaticMethod();
    
        }
    }
    

提交回复
热议问题