Static method in java

后端 未结 8 1839
自闭症患者
自闭症患者 2020-12-08 12:37

I heard that static methods should use only static variables in java. But, main method is also static, right?

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 13:17

    Your question: is the statement " static methods should use only static variables" correct?

    No. The statement is not correct.

    The correct statement will be "static methods can only use those instance variables that are defined static"

    Take a look at following code and read the comments:

    Class A{
        int i;
        static int j;
    
        public static void methodA(){
            i = 5; //cannot use since i is not static
            j = 2; //can use.
    
            int k = 3; //k is local variable and can be used no problem
    
            **EDIT:**//if you want to access i
            A a = new A();
            //A.i = 5; //can use.  
            a.i = 5; // it should be non-capital "a" right?
        }
    }
    

提交回复
热议问题