Static method in java

后端 未结 8 1800
自闭症患者
自闭症患者 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:16

    One important thing is that unless u create an instance of an class the instance variables don't exist practically it means JVM doesn't that there os an variable like int i unless u create an instance for that class. so, using an instance variable in a static method is an compilation error.

    class A{
        int i;
        static int j;
        static int b(){
            i=10; // cannot be found 
            A a= new A();
            a.i=10;//can be found in a's instance
        }
    }
    

    But, we can use instance variables in instance methods because, instance methods are only called when object created so there is no problem in using instance variables inside it.

    Hope ur clear about these things!

    0 讨论(0)
  • 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?
        }
    }
    
    0 讨论(0)
提交回复
热议问题