Java keyword final use method in detail

  • 2020-04-01 02:25:00
  • OfStack

It says, "this part cannot be modified." There are two reasons for not wanting to be changed: efficiency, design. There are three cases where final is used: data, methods, and classes.

I. final data

Sometimes data constancy is useful to reduce the burden on the system at runtime. For these constant data I can call them constants. "Constants" are mainly used in the following two places:
1, compile time constant, never change.
2. When the runtime is initialized, we hope it will not be changed.
For compile-time constants, they are initialized during class loading, so they are immutable after class loading, and can be substituted into any formula that USES them at compile time. Of course, for compile-time constants, you can only use primitive types, and you must initialize them at definition time.
For variables that we want to represent differently depending on the object, but don't want to change, we can use runtime constants. For run-time constants, it is both a basic data type and a reference data type. The basic data type is immutable for its content, while the reference data type is immutable for its reference, and the object content specified by the reference is mutable.


public class Person {
    private String name;
    Person(String name){
  this.name = name;
    }

    public String getName() {
  return name;
    }
    public void setName(String name) {
  this.name = name;
    }
}
public class FinalTest {
    private final String final_01 = "chenssy";    //Compile-time constants that must be initialized and cannot be changed
    private final String final_02;    //Constructor constant, which is initialized when an object is instantiated

    private static Random random = new Random();
    private final int final_03 = random.nextInt(50);    //Use random Numbers for initialization

    //reference
    public final Person final_04 = new Person("chen_ssy");    //final Point to the reference The data type 

    FinalTest(String final_02){
  this.final_02 = final_02;
    }

    public String toString(){
  return "final_01 = " + final_01 +"   final_02 = " + final_02 + "   final_03 = " + final_03 +
   "   final_04 = " + final_04.getName();
    }

    public static void main(String[] args) {
  System.out.println("------------ Create the object for the first time ------------");
  FinalTest final1 = new FinalTest("cm");
  System.out.println(final1);
  System.out.println("------------ Create the object a second time ------------");
  FinalTest final2 = new FinalTest("zj");
  System.out.println(final2);
  System.out.println("------------ Modify the reference object --------------");
  final2.final_04.setName("chenssy");
  System.out.println(final2);
    }
}
------------------
Output:
------------ Create the object for the first time ------------
final_01 = chenssy   final_02 = cm   final_03 = 34   final_04 = chen_ssy
------------ Create the object a second time ------------
final_01 = chenssy   final_02 = zj   final_03 = 46   final_04 = chen_ssy
------------ Modify the reference object --------------
final_01 = chenssy   final_02 = zj   final_03 = 46   final_04 = chenssy

The only point here is: don't assume that some data is final and know its value at compile time. Final_03 tells you that. In this case, it initializes with random Numbers.

2. Final method

All final annotated methods cannot be inherited or changed, so the first reason to use final methods is method locking to prevent any subclasses from modifying them. As for the second reason, efficiency, which I don't understand very well, I'll quote it online: in early implementations of Java, specifying a method as final gave the compiler permission to make all calls to that method inline. When the compiler found a final method call command, it will according to your own careful judgment, skip the inserted code this way of normal calls and execution method invocation mechanism (press parameters into the stack, jumped method executes the code, and then jump back to clean up the stack of parameters, process the return value), and with the copy of the actual code in the method body method call. This will eliminate the overhead of method invocation. Of course, if a method is large, your code will inflate, and you may not see any performance gains from embedding because the performance gains will be reduced by the amount of time spent in the method.
To this paragraph of words understanding I am not very understand to copy, that Java cow person can explain explain below!!
A parent class's final method cannot be overridden by a subclass, which means that a subclass cannot have exactly the same method as the parent class.


public class Custom extends Person{
    public void method1(){
  System.out.println("Person's  method1....");
    }

//      Cannot override the final method from person: a subclass Cannot override the final method from a parent class
//    public void method2(){
//  System.out.println("Person's method2...");
//    }
}

Third, final class

If a class is modified with final, that class is the final class, and it does not want or allow others to inherit it. For security or other reasons in programming, we don't allow any changes to the class, and we don't want it to have subclasses, so we can use final to modify the class.
For a class that is final, its member variables can be final or non-final. If it is defined as final, then the rules for final data also apply to it. Its methods add final automatically, because final classes cannot be inherited, so this is the default.

Final parameters

  In practice, in addition to modifying member variables, methods and classes with final, we can also modify parameters. If a parameter is modified with final, it means that the parameter is immutable.
If we modify The parameter in The method, The compiler will prompt you: The final local variable I cannot be assigned. It must be blank and not using a compound assignment.


public class Custom {
    public void test(final int i){
//I++;         -- the final parameter cannot be changed
  System.out.println(i);
    }

    public void test(final Person p){
     //P = new Person ();       -- the final parameter is immutable
     p.setName("chenssy");
    }
}

It is very useful to modify the parameter with final in the inner class. In order to maintain the consistency of the parameter in the anonymous inner class, if the parameter of the method is needed to be used in the inner class, the parameter must be final.

Final and static

When final and static are used together, a magical chemical reaction will occur. When they are used at the same time, they can modify both member variables and member methods.
For a member variable, which cannot be changed once assigned, we call it a "global constant." You can access it directly through the class name.
For member methods, it is not inheritable and cannot be changed. You can access it directly through the class name.  


Related articles: