Static method in java

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

    Maybe this piece of code will enlighten you:

    public class Main {
    
        private String instanceField = "Joe";
    
        private void instanceMethod() {
            System.out.println("Instance name=" + instanceField);
        }
    
        public static void main(String[] args) {
    
            // cannot change instance field without an instance
            instanceField = "Indy"; // compilation error
    
            // cannot call an instance method without an instance
            instanceMethod(); // compilation error
    
            // create an instance
            Main instance = new Main();
    
            // change instance field
            instance.instanceField = "Sydney";
    
            // call instance method
            instance.instanceMethod();  
        }
    }
    

    So you cannot access instance members without an instance. Within the context of a static method you don't have a reference to an instance unless you receive or create one.

    Hope this helps.

提交回复
热议问题