Static method in java

后端 未结 8 1807
自闭症患者
自闭症患者 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条回答
  •  Happy的楠姐
    2020-12-08 13:15

    To access non-static fields (instance variables) you need to have an instance.
    Inside a non-static method, this is used as default instance:

    class AnyClass  {
    
        private String nonStaticField = "Non static";
    
        void nonStaticMethod() {
            this.nonStaticField = "a text";  // accessing field of this
            nonStaticField = "a text";       // same as before
        }
    }
    

    Inside a static method there is no this to use as default instance, but you can1 still access instance variables if you provide the instance:

    class AnyClass {
    
        private String nonStaticField = "Non static";
    
        static void staticMethod() {
            AnyClass example = new AnyClass();
            example.nonStaticField = "new value for non-static field";
        }
    }
    

    1 - the field must also be accessible by Java's access control (declared public or in the same class ...)

提交回复
热议问题