Have a brief talk java Medium final keyword
In everyday code ,final Keywords are also commonly used . Its main application is in three aspects :

1) decorator ( I've seen it for a while , But I haven't used it yet );
2) Modification methods ( have seen , I haven't written );
3) Decorate data .

that , We mainly discuss it from the following aspects , Mainly the third point .

One 、final Modifying classes and methods
final The decorated class cannot be inherited ( for example : String, Integer, Double, ....);
final The decorated method cannot be overridden ( for example : AtomicInteger Most of the methods in )

Two 、final Decorate data
1. final Modifying variables
  Divided into local variables and global variables . If it's a global variable , Whether you use it or not , Must and can only be assigned once ;
for example :

public class FinalTest {
private final int i;
}

If not assigned , Compile error will be reported : Variable "xxx" might not have been initialized.

If it's a local variable , If not used , It can be unassigned .( Of course , You have to make sure your project manager doesn't kill you ).

1.1 final Modify the basic data types and invariant objects ( for example : String, Packaging and jdk8 New date time class library ) That's really nothing to change ( The reference relationship between reference and object , Object content ( The basic type is the value ) You can't change the value of ). for example :

 public class FinalTest {
public static void main(String[] args) {
final int a = 10;
final LocalDate localDate = LocalDate.now();
}
}

If you are right again a perhaps localDate Assign a value : Compile error will be reported : cannot assign a value to final variable 'xxx'.

so to speak ,final The modification of a reference to an immutable object is almost the same as the modification of a reference to an underlying type .

1.2 For mutable objects ( frequently-used StringBuilder, All kinds of common (List, Set, Map) Collection implementation class for ),final Only the previous reference relationship between reference and object can be guaranteed unchanged , The content of the object cannot be guaranteed ( For example, the value of a field , The number of elements in the container ) unchanged .

 public class FinalTest {
public static void main(String[] args) {
final StringBuilder sb = new StringBuilder("sb ");
System.out.println("sb: " + sb);
sb.append("changed");
System.out.println("sb: " + sb);
}
}

-------------------------------------------------------------------------------
Output :
sb: sb
sb: sb changed

3. final The type of value decorated (8 Basic data types + String) Will be optimized to compile time constants

Here we use String Let's test it :

public class FinalTest {
public static void main(String[] args) {
String a = "a";
String ab = a + "b";
System.out.println(ab == "ab"); final String finalA = "a";
String finalAB = finalA + "b";
System.out.println(finalAB == "ab");
}
}

-------------------------------------------------------------------------------
Output :
false
true

here , We can decompile FinalTest.class file :

1 public class FinalTest {
2 public FinalTest() {
3 }
4
5 public static void main(String[] args) {
6 String a = "a";
7 String ab = a + "b";
8 System.out.println(ab == "ab");
9 String finalA = "a";
10 String finalAB = "ab";
11 System.out.println(finalAB == "ab");
12 }
13 }

Contrast No 7 Xing He 10 Line discovery , The first 7 Line variable ab The value of is unknown at compile time ( Actually in the run time , The first 7 Line of code is executed like this :

String ab = new StringBuilder("").append(a).append("b").toString;

And in the StringBuilder#toString() In the way ,new A new one String example , therefore ab and "ab" Not an example , So the first 8 Line output false.), And the first 10 Line variable finalAB The value of is known at compile time , because String Cache properties of constant pools , bring finalAB and "ab" It's the same example , So the first 11 Line output true.

This point , Sometimes it brings problems . Take the following example :

 1 class A{
2 public static final int A = 10;
3 }
4
5
6 class B{
7 public B(){
8 System.out.println(A.A);
9 }
10 }

From the source code , You can see class B and class A There's something about it . But actually , Compiled class Bytecode , class A And the class B It doesn't matter . After the compilation , The first 8 That's ok A.A Has been replaced by 10 了 . If this time , I changed this A The value of a constant in , And then just to A recompile , It leads to classes B Of class It's still in the file 10. This may give the program some problems running the code .


final Modify method parameters
`1 This is in jdk It's rare in China , But it's often seen in framework code . The basic function is to prevent method callers from assigning values to parameters ( In fact, this is also a kind of agreement ). For example, such a scene : Now there's a set of tasks to perform ( Tasks can be parallel ), After this group of tasks is completed , You need to clean up the cache ; The possible code is like this

 List<Task> tasks = ...;
CountDownLatch countDoenLatch = new CountDownLatch(tasks.size());
for(Task task : tasks){
// Thread pool executes asynchronously
WORKER.submit(task);
}
cleanCache(countDownLatch);
-----------------------------------------------------------------------------------------------------
public void cleanCache(final CountDownLatch countDownLatch){
countDownLatch.await();
...
}

here cleanCache() Method CountDownLatch You need to use final modification .( If the countDownLatch Reassign , Subsequent calls countDownLatch.await() It leads to an indefinite wait )

Summary :
final When modifying references , Just make sure that a reference can and can only establish a reference relationship with an object ( Basic type of value ), As for whether the content of the object to which the reference refers can be changed , And here, final It doesn't matter , It's about whether the object is invariant or not . ( Popular will , Use final When modifying a reference , This final The only thing that can be controlled is this reference , As for the object to which the cause is directed, it can be immutable , It doesn't care .)

Have a brief talk java Medium final More articles about keywords

  1. elementary analysis Java Medium final keyword ( Reprint )

    since http://www.cnblogs.com/dolphin0520/p/3736238.html Reprint One .final Basic usage of keywords stay Java in ,final Keywords can be used to decorate classes . Methods and variables ( Include ...

  2. About Java Medium final keyword

    Java Medium final Keywords are used to limit user behavior , To put it bluntly , It's used to limit us programmers .final Can be used to modify : Variable . Method . class . 1)Java final variable final When used to modify variables , ...

  3. In depth understanding of Java Medium final keyword

    Java Medium final Keywords are very important , It can be applied to classes . Methods and variables . In this article, I will show you what is final keyword ? Put the variable , Methods and classes are declared as final What does it stand for ? Use final What are the benefits of ? In the end, there are also some ...

  4. elementary analysis Java Medium final keyword

    elementary analysis Java Medium final keyword talk about final keyword , Many people must be familiar with it , It's often used when using anonymous inner classes final keyword . in addition ,Java Medium String A class is just a final class , So today we're going to ...

  5. ( turn ) In depth understanding of Java Medium final keyword

    from :http://www.importnew.com/7553.html Java Medium final Keywords are very important , It can be applied to classes . Methods and variables . In this article, I will show you what is final keyword ? Put the variable , Fang ...

  6. [ Reprint ] elementary analysis Java Medium final keyword

    elementary analysis Java Medium final keyword talk about final keyword , Many people must be familiar with it , It's often used when using anonymous inner classes final keyword . in addition ,Java Medium String A class is just a final class , So today we're going to ...

  7. Reprint : elementary analysis Java Medium final keyword

    talk about final keyword , Many people must be familiar with it , It's often used when using anonymous inner classes final keyword . in addition ,Java Medium String A class is just a final class , So today we're going to learn about final How to use this keyword . Next ...

  8. java Medium final keyword

    talk about final keyword , Many people must be familiar with it , It's often used when using anonymous inner classes final keyword . in addition ,Java Medium String A class is just a final class , So today we're going to learn about final How to use this keyword . Next ...

  9. elementary analysis Java Medium final keyword ( turn )

    talk about final keyword , Many people must be familiar with it , It's often used when using anonymous inner classes final keyword . in addition ,Java Medium String A class is just a final class , So today we're going to learn about final How to use this keyword . Next ...

Random recommendation

  1. linux Basics - disk array (RAID) Details of the example

    disk array (RAID) Details of the example raid Technical classification soft raid technology hard raid technology Raid and lvm The difference between Why choose to use raid RAID Detailed explanation RAID-0 RAID-1 RAID-5 Raid-10 R ...

  2. encounter makeblock

    Last week I went out for dinner and saw a restaurant named “ Maker Workshop ” My company is advertising , I was thinking that the company had money , That's all the advertising , I didn't think about it in detail. Let president Han scan their QR code , I came back to search this company , I rely on , It's open source hardware : Look at the machines again ...

  3. c language knowledge ( Find out more than 2 Students who failed in the exam )

    1. First, define a student structure ( The structure contains a Score Structure ): typedef struct score{ float chinese;// Chinese achievement float english;// English scores flo ...

  4. Please give asynchronous load js programme

    Please give asynchronous load js programme , Not less than two kinds By default javascript It's loaded synchronously , That is to say javascript Is blocked when loading , The elements behind it have to wait javascript It can only be reloaded after loading , For some, it doesn't mean very much ...

  5. QM5_Didstribution

    Basic Concepts Probability distribution Discrete distribution ( Discrete distribution ) The distribution of the discret ...

  6. MySQL8.0 on Windows Next reset root Cryptographically BUG

    A lot of people know that MySQL forget root The password can be passed through skip-grant-tables For the time being MySQL, To modify root password , But on the one hand, this way has security risks , On the other hand, it doesn't really apply to Windows ...

  7. UI The designer gave px Unit of measure , How Android translates into dp?

    quite a lot UI Engineers to fit IOS, Often take IOS Mobile phone reference model , Designed UI Draft only PX Dimensioned . They don't understand either Android Of dp and sp What's going on with the unit . At this time we Android If engineers don't pay attention to how to switch , ...

  8. Play chess win32 note

    Playing chess win32 note   One :Windows How the program works One .Windows Four module programs 1.1 Console program There's no window of your own ,dos- Display or run programs , entrance mian() 1.2 Window program It has its own window ,w ...

  9. vue+axios Perfect implementation of front-end route interception

    One . Route blocking 1. First, in the router Of index.js Configure a custom field in requireAuth, Use this field to determine whether you need to log in to enter the route . If you have logged in, enter the route , Otherwise, enter the login page . This is the routing configuration : ...

  10. IIS Load balancing -Application Request Route Explain the first part in detail : ARR Introduce

    IIS Load balancing -Application Request Route Explain the first part in detail : ARR Introduce When it comes to load balancing , I believe we are no longer strangers , This series mainly introduces IIS Load balancing software that can be used in : Microsoft Applica ...