当前位置:网站首页>Deeply analyze the usage of final keyword

Deeply analyze the usage of final keyword

2022-06-22 08:40:00 BreezAm

Fu Taogong Cool breeze Through the ages , Who else is Yu , How dare you call me
 Insert picture description here
Personal blog address :http://blog.breez.work


Introduce

final For declaration attribute 【 Properties are immutable 】、 Method 【 Method cannot be overridden 】、 class ( Except for abstract classes )【 Class cannot be inherited 】

analysis

final attribute

By final Embellished Variable is immutable .【 Reference immutable

public class FinalTest {
    
    public static void main(String[] args) {
    
        final StringBuffer s = new StringBuffer("Hello");
        s.append(" World");
        System.out.println(s); // Output Hello World
    }
}

public class FinalTest {
    
   public static void main(String[] args) {
    
       final StringBuffer s = new StringBuffer("Hello World");
       s = new StringBuffer("Hello world"); // Compiler error 
   }
}

As can be seen from the above final refer to Reference immutable , That is, it can only point to the one pointed to during initialization object , Don't care about pointing to objects Content The change of . So be final Embellished Variable Must be initialized .

How to initialize :

  1. Initialize at definition time
final String name="BreezAm";
name="change"; // Compile error 
  1. final Member variables can be set in In initial block initialization , But it cannot be initialized in a static block .
  • Initialize... In the initialization block :【 Compile and pass
public class FinalTest {
    
    private final String name;// Define a member variable 
  
    {
    
        name = "BreezAm";// Initialize member variables in the initialization block name
    }

    public static void main(String[] args) {
    
        FinalTest test = new FinalTest();
        String name = test.name;
        System.out.println(name);//BreezAm
        
        test.name="change";// Compiler error 
    }
}

Try to be in Static initialization block In the initialization final Variable 【 Compiler error

public class FinalTest {
    
    private final String name;//  Compiler error 

    static{
    
        name = "BreezAm"; // Compiler error , Even if the name It has been initialized during definition, and an error will be reported during compilation 
    }
    
    public static void main(String[] args) {
    
        FinalTest test = new FinalTest();
        String name = test.name;
        System.out.println(name);//BreezAm
    }
}
  1. static state final Member variables can be set in Static initialization block In the initialization , But not in Initialization block In the initialization .
  • stay Static initialization block Initializing member variables in 【 Compile and pass
public class FinalTest {
    
    private static final String name;//  Define a static 、 Immutable variables 

    static {
    
        name = "BreezAm";// Initialize... In a static initialization block 
    }

    public static void main(String[] args) {
    
        String name = FinalTest.name;
        System.out.println(name);//BreezAm
    }
}
  • Try to be in Static initialization block Initializing member variables in 【 Compiler error
public class FinalTest {
    
    private static final String name;//  Compiler error 

    {
    
        name = "BreezAm";// Initialize... In the initialization block 
    }

    public static void main(String[] args) {
    
        String name = FinalTest.name;
        System.out.println(name);//BreezAm
    }
}
  1. In class Constructors In the initialization , but static state final Member variables Can not be Initializes in the constructor .
  • stay Constructors In the initialization The static final Member variables 【 Compile and pass
public class FinalTest {
    
    private final String name;//  Define a member variable 【 uninitialized 】

    public FinalTest() {
    
        name = "BreezAm";// Initialize... In the constructor final A member variable of type 
    }

    public static void main(String[] args) {
    
        FinalTest test = new FinalTest();
        String name = test.name;
        System.out.println(name);//BreezAm
    }
}

final Method

When a method is declared as final when , The method No subclasses are allowed to override This method , but Subclasses can still use This method .[ Be careful final Methods can be overloaded ]


in addition , There is another one called inline( inline ) The mechanism of , When a call is declared as final Method time , Direct the method body Insert into the callout , Instead of making method calls ( Be similar to C++ Medium inline), To do so Can improve the efficiency of the program .

Case study :

/** *  Parent class  */
public class Father {
    
    /** *  Write a final Method  */
    public final void doAction(){
    
        System.out.println(" I am a final Method 、 I can't be rewritten , But you can use Oh ! Cinderella !!");
    }
}

Subclasses attempt to override final Method 【 Compiler error

/** *  Subclass  */
public class Children extends Father {
    

    public final void doAction(){
     // Compiler error 、 Because the parents doAction The method is final Type of , So it can't be rewritten 

    }
	
    public static void main(String[] args) {
    

    }
}

Use... In the parent class final Method 【 Compile and pass

/** *  Subclass  */
public class Children extends Father {
    
    public static void main(String[] args) {
    
        Children children = new Children();
        children.doAction();
    }
}

Output :

 I am a final Method 、 I can't be rewritten , But you can use Oh ! Cinderella !!

Subclasses overload... In the parent class final Method

/** *  Subclass  */
public class Children extends Father {
    

    /** *  Override the parent class declared as final Methods  * @param a * @param b */
    public final void doAction(int a,int b){
     //  It can be reloaded , ha-ha , I found out 
        System.out.println("a:"+a);
        System.out.println("b:"+b);
    }
    public static void main(String[] args) {
    
        Children children = new Children();
        children.doAction(20,30);
    }
}

Output :

a:20
b:30

final Parameters

Used to express this Parameters In this Internal function Not allowed to be modified

Case study :

public class FinalTest {
    
    /** *  Write a program with parameters as final Methods  * * @param name */
    /*public void doActionFinal(final String name) { name = " I want to change name, But the compilation report is wrong , sorry !!"; // Compile not pass  }*/

    /** *  Write a non - final Parameter method  * * @param name */
    public void doAction(String name) {
    
        System.out.println(" Before the change :" + name);

        name = "name The parameter is not final Of , I modified it successfully , One word : Bashi !"; // Compile and pass 
        System.out.println(" After modification : " + name);
    }

    public static void main(String[] args) {
    
        FinalTest test = new FinalTest();
        //test.doActionFinal("BreezAm");

        test.doAction("BreezAm");

    }
}

Output :

 Before the change :BreezAm
 After modification :  name The parameter is not final Of , I modified it successfully , One word : Bashi !

final class

When a class is declared final when , Such kind uninheritable , All the methods are Can't be rewritten . But this It doesn't mean final Class member variables are also immutable , To do it final The member variables of a class cannot be changed , Member variables must be given increase final modification . Be careful : A class cannot be declared as abstract, It was declared that final【 Abstract classes cannot be declared as final】.

An attempt to inherit is declared as final Class 【 Compile failed

/** *  Parent class  */
public final class Father {
    
}

/** *  Subclass  */
public class Children extends Father {
      // Compiler error 

}

Try to put a abstract Class declared as final【 Compile failed

/** *  Parent class  */
public final abstract class Father {
     // Compile failed , Abstract classes cannot be declared as final

}

modify final Member variables of class

/** *  Parent class  */
public final class Father {
    
    private String name = "BreezAm";
    private final int num = 2018010110;

    public void doAction() {
    
        name = " Cool breeze ";// modify final Class's non final Member variables   Compile and pass 

        num = 2019010110;// modify final Class final Member variables   Compile failed 
    }
}

 Insert picture description here

原网站

版权声明
本文为[BreezAm]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220833350348.html