static关键字可用于3种场景:
- 静态变量
- 静态方法
- 静态代码块
静态块是一个语句块Java class
,它将在类首次加载到JVM时执行。
- 静态方法也不能被覆盖,因为它是类的一部分而不是对象?
- 为了能够从静态方法访问非静态变量,它们需要是静态成员变量。
Details on Static method
- How to identify? Just check this first. Do you need an class object to access static method? If you don’t need an object then it’s Static method.
- You need to use static keyword in order to specify static method
- Better use keyword static if that method is not going to change throughout your project at runtime.
- You can’t override static method.
我们必须创建Class的实例来访问非静态方法。
当使用关键字声明变量时static
,它被称为a class variable
。所有实例共享变量的同一副本。可以使用类直接访问类变量,而无需创建实例。
Benefits of static variables:
- constants can be defined without taking additional memory (one for each class)
- constants can be accessed without an instantiation of the class
Benefits of static methods:
- instance-independent behavior can be defined without fear of accidental interaction with an instance of the class