1. The static keyword is used to declare static variables independent of objects. No matter how many objects a class instantiates, there is only one copy of its static variables. Static variables are also called class variables. Local variables cannot be declared as static variables.
2. The static keyword is used to declare static methods independent of objects.
Example
class InstanceCounter { private static int num = 540; // 私有的静态变量 public static int getNum(){ // 公有的静态方法 return num; } // 构造方法 自动执行 构造方法中可以使用this 和es6中的构造函数一样 public InstanceCounter() { System.out.println(this.getNum()); // this.getNum() == getNum() this.num++; // this.num == num } } public class demo1{ public static void main(String[] args) { new InstanceCounter(); System.out.println(InstanceCounter.getNum()); // 打印静态方法 类名调用 541 } }
The above is the detailed content of How to use static modifier in java. For more information, please follow other related articles on the PHP Chinese website!