• 周六. 10 月 5th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Finishing notes with the final keyword in Java

King Wang

1 月 3, 2022

final Keywords can modify member variables , Method , And local variables . If you declare a reference as finall type , Then the reference will not be changed again , By final After retouching , It’s an immutable thing .

final Variable

By final Decorated variable ( Member variables and local variables ) It’s called “as” final Variable , It’s stored in a constant pool .final Variables often and static Use keywords together , As constant .

use final Decorated variable , Only one assignment operation can be performed , And the whole life cycle is unchangeable .

But when it comes to base types and reference types ,final There are subtle differences in the effect of keywords :

class Value {

int v;
public Value(int v) {

this.v = v;
}
}
public class TestFinal {

final int f1 = 1;
// value1 = 4; // No more for value1 assignment 
final int f2;
public TestFinal() {

f2 = 2;
}
public static void main(String[] args) {

final int value1 = 1;
final double value2;
value2 = 2.0;
final Value value3 = new Value(1);
value3.v = 4;
}
}

value3 It’s a reference variable ,final Modifies the reference variable , Limit the value of the reference variable to be immutable , That can’t leave value3 Again, quote a Value object , But the value of the reference object can be changed .

On the other hand , because final The value of the data is unchangeable , So it has to be assigned before use . There are two ways :

  • Assign values directly when declaring
  • Assignment in constructor

Last but not least : Use at the same time static and final The decorated member only occupies an unchangeable storage space in memory .

final Method parameter

A lot of times , When we pass variables as parameters , Will ask that the values passed in the past will not change . So you’ll use final To embellish . That is, add… Before the parameter final Key words can be used , It means that in the whole method , Do not change the value of the parameter .

public void finalFunc(final int i,final Value value){

//i=5; //error, Can't change i Value 
//value=new Value(); //error, Cannot change the value of this reference 
value.v=111; // You can change the value of the reference object 
}

final Method

final The method of decoration , Represents that the method cannot be overridden by subclasses . If you think a method is fully functional , If there is no need to change in the subclass , You can declare this method as final.final Method than not final The method should be quick , Because it’s statically bound at compile time , No need to bind dynamically at runtime . About private and final There is also a connection between keywords and all of the private Methods are implicitly specified as yes final Of , Because you can’t use it outside of a class private Method , So it can’t be covered . Here is final Examples of methods :

class PersonalLoan {

public final String getName() {

return "personal loan";
}
}
class CheapPersonalLoan extends PersonalLoan {

@Override
public final String getName() {

return "cheap personal loan"; // compilation error: overridden method is final
}
}

final class

Use final The class to be decorated is called final class .final Classes are usually fully functional , They cannot be inherited .java Many of them are final Of , for example String, Interger And other packaging . Here is final Class :

final class PersonalLoan{

}
class CheapPersonalLoan extends PersonalLoan{
 //compilation error: cannot inherit from final class

final Keyword advantages

  • Improved performance ,JVM and java Application will cache final Variable
  • final Variables can be shared safely in a multithreaded environment , Without any additional synchronization overhead .
  • Use final keyword ,JVM Would be right. 、 Optimization of variables and classes .

To create an immutable class, use final keyword . Immutable class means that its object cannot be changed once it is created .String Is the representative of immutable classes . Immutable classes have many advantages , For example, their objects are read-only , It can be safely shared in a multithreaded environment , No extra synchronization overhead

A few easy to mix

1. Class final What’s the difference between a variable and a normal variable

When used final When acting on a member variable of a class , Member variables ( Note that the member variables of the class , Only the variables need to be assigned before they are initialized ) Initialization assignments must be made at definition time or in the constructor , and final Once the variable has been initialized and assigned , It can’t be assigned any more .

public class Test {

public static void main(String[] args) {

String a = "hello2";
final String b = "hello";
String d = "hello";
String c = b + 2;
String e = d + 2;
System.out.println((a == c)); //true
System.out.println((a == e)); //false
}
}

The result is final The difference between variables and ordinary variables , When final Variables are basic data types and String Type , If you know the exact value during compilation , The compiler uses it as a compile time constant . That is to say, in the use of final Where the variables are , This is equivalent to the constant of direct access , There is no need to determine at run time . This and C Macro substitution in language is a bit like .

So in the code above , Because of the variable b By final modification , So it’s treated as a compiler constant , So in the use of b The variable will be changed directly b Replace with its value . And for variables d However, the access needs to be done through links at run time . But be careful , Only during compilation can we know exactly final In the case of variable values , The compiler does this optimization , For example, the following code will not be optimized :

public class Test {

public static void main(String[] args) {

String a = "hello2";
final String b = getHello();
String c = b + 2;
System.out.println((a == c)); //false
}
public static String getHello() {

return "hello";
}
}

2. By final Does the modified reference variable point to variable object content

public class Test {

public static void main(String[] args) {

final MyClass myClass = new MyClass();
System.out.println(++myClass.i); // Output is 1
}
}
class MyClass {

public int i = 0;
}

Indicates that the reference variable is final After retouching , You can’t point to other objects , But the content of the object it points to is variable .

3.final and static

It’s easy to put static and final Keyword confusion ,static A member variable is used to indicate that only one copy is saved , and final Is used to ensure that variables are immutable .

public class Test {

public static void main(String[] args) {

MyClass myClass1 = new MyClass();
MyClass myClass2 = new MyClass();
System.out.println(myClass1.i);
System.out.println(myClass1.j);
System.out.println(myClass2.i);
System.out.println(myClass2.j);
}
}
class MyClass {

public final double i = Math.random();
public static double j = Math.random();
}

Run this code and you’ll find , Two at a time j The value is the same , and i But the values are different . From here we can know final and static The difference between variables .

发表回复