How to use static and final in Java?

In Java, static and final are two keywords used to modify classes, methods, and variables.

  1. Static keyword:
  1. Static classes cannot be instantiated and can only be accessed directly through the class name to modify a class.
  2. Static methods are class methods that can be directly called using the class name, without the need to create an instance of the class.
  3. 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("这是一个实例方法");
    }
}
  1. final keyword:
  1. Final classes cannot be inherited and do not allow other classes to inherit from them.
  2. Final methods cannot be overridden by subclasses and can only be used directly by the subclasses without modification.
  3. 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:

  1. “Static and final can both be used to modify variables, indicating the declaration of a static constant.”
  2. In non-static methods, static members can be accessed directly, but in static methods, non-static members cannot be accessed directly.
bannerAds