1. What is final

Final is a Java keyword that stands for “final, immutable”.

Final is like a lock, and the key to the lock is lost, so everything he modifies is final.

In real life, we often use English expressions related to final.

The final examCopy the code

Let’s move on to the use of final in Java.

2. The final usage

2.1 Final variables can be assigned only once

Such as:

The name of the final modifier in the above example represents the final variable.

2.2 Final modified classes cannot be inherited

To take a bad example, a class modified by final is like a eunuch, so it has no descendants, no one can inherit it.

2.3 Final modification method cannot be overridden

Just like Nuwa made a man this trick neither men nor women.

2.4 Final modified references cannot be redirected to other objects

In the above example, the final animal1 reference can no longer point to a new object, but the object that animal1 points to can also change its property values, for example:

public class Animal {
    String name;
    public static void main(String[] args) {
        final  Animal animal1 = new Animal();
        animal1.name = "Husky";
        System.out.println(animal1.name);
        System.out.println("-- -- -- -- -- -- -- -- -- -- -");
        animal1.name = "Sheepdog"; System.out.println(animal1.name); }}Copy the code

Running results:

This is equivalent to somewhere issues after limiting room order, everyone can buy a suite only by id card, although cannot buy the 2nd suite, but THE furniture in the house I can change casually.

Instance variables modified by 2.5 Final must be initialized

Because final means final, so if you don’t assign it, it’s null at first, and you can assign it later, and it contradicts final.

2.6 Final and static

In real development, we generally don’t go so far as to decorate a class with a final so that other classes don’t inherit. Nor does it go so far as to decorate a method with final so that no other class can override it. And not to the extent that final is used to modify an object, it feels like the object is awesome.

We usually use final with static to represent constants.

Such as:

// OSS related constant classes
public class ConstantsOSS {
    
    public static final String DEFAULT_CHARSET = "UTF-8";

    public static final Integer INPUT_BUFFER_SIZE = 256;

    public static final int GB = 1024 * 1024 * 1024;
}
Copy the code

Because static variables are class-specific, you can use the class name. Static and final variables are permanently unmodifiable.

We use the class name directly. The variable name gets the data, for example:

public class FinalTest {
    public static void main(String[] args) { System.out.println(ConstantsOSS.DEFAULT_CHARSET); System.out.println(ConstantsOSS.GB); System.out.println(ConstantsOSS.INPUT_BUFFER_SIZE); }}Copy the code