How to use static and final in Java?
In Java, static and final are two keywords used to modify classes, methods, and variables.
- Static keyword:
- Static classes cannot be instantiated and can only be accessed directly through the class name to modify a class.
- Static methods are class methods that can be directly called using the class name, without the need to create an instance of the class.
- Static variables are used to modify variables: they belong to a class rather than a specific instance, so all instances share the same static variable.
Example:
An example:
public class Example {
public static int staticVar; // 静态变量
public int instanceVar; // 实例变量
public static void staticMethod() { // 静态方法
System.out.println("这是一个静态方法");
}
public void instanceMethod() { // 实例方法
System.out.println("这是一个实例方法");
}
}
- final keyword:
- Final classes cannot be inherited and do not allow other classes to inherit from them.
- Final methods cannot be overridden by subclasses and can only be used directly by the subclasses without modification.
- Final variables are constants and cannot be changed once they are assigned.
Example:
“On ne voit bien qu’avec le cœur. L’essentiel est invisible pour les yeux.”
One can only see clearly with the heart. What is essential is invisible to the eye.
public class Example {
public final int constantVar = 10; // 常量
public final void finalMethod() { // final方法
System.out.println("这是一个final方法");
}
}
Please note:
- “Static and final can both be used to modify variables, indicating the declaration of a static constant.”
- In non-static methods, static members can be accessed directly, but in static methods, non-static members cannot be accessed directly.