Static method in java

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

    A static method is called on a class instance and not to an object of a class. This means, that a static method is not able to access instance variables, because they are only instantiated in an object.

    If you want to access an instance variable with a static method, you have to declare that variable as static.

    public class Test {
        private static int value = 0;
    
        public static void main(String[] args) {
            value++;
        }
    }
    

    But to be honest, it's not the best idea to write everything in static methods. It's better to use the main method to instantiate new objects.

提交回复
热议问题