Java learning road-the use of final keywords

Java learning road-the use of final keywords

Overview

In Java, the final keyword can be used to modify classes, methods, and variables (including member variables and local variables).

Final means final, adding final classes, methods, and variables to Java programs means that they cannot be modified.

One, final modification class

When a class is modified with final, it indicates that the class cannot be inherited.

In other words, if we hope that a class cannot be inherited, it can be decorated with final. In Java, classes such as String and System are final modified classes.

The member variables in the final class can be set to final as needed, but note that all member methods in the final class will be implicitly designated as final methods.

final class Person {
    
    
    
}

Two, final modification method

There are two reasons for using the final method. The first reason is to lock the method in case any inherited classes modify its meaning; the second reason is efficiency. In earlier versions of Java implementation, final methods will be converted to inline calls. But if the method is too large, you may not see any performance improvement brought by the inline call. In recent Java versions, there is no need to use final methods for these optimizations. ——"Java Programming Thought"

Methods modified by final cannot be overridden by subclasses. For example, in Object, the getClass() method is final, we cannot override this method, but the hashCode() method is not modified by final, we can override the hashCode() method.

class Person {
    
    
    final public void say() {
    
    
        System.out.println("Hello, world!");
    }
}

Three, final modified variables

The final modified variable, if it is a basic data type, then its value cannot be modified; if it is a reference object type, then its reference address cannot be modified.

Precautions:

  • For final modified attributes, the attribute assignment position can include display initialization, initialization in the code block, initialization in the constructor, and cannot be assigned in the method;
  • The final modified formal parameter variables can only be used in methods and cannot be modified;
  • You can use static final to decorate class global constants.
public class Demo {
    
    
    public static void main(String[] args)  {
    
    
        final Person p = new Person();
        p.age = 15;
        System.out.println(p.age);

        final int age = 18;
//        Cannot assign a value to final variable 'age'
//        age = 15;
    }
}

class Person {
    
    
    int age = 18;
}

Guess you like

Origin blog.csdn.net/qq_43580193/article/details/112612181