In java, final can be used to modify classes, methods and variables. The final modified class means that the class cannot be inherited by any other class, which means that this class is a leaf class in an inheritance tree, and the design of this class has been considered perfect and does not need to be modified or extended. The method in the final modified class means that the class cannot be inherited by any other class and cannot be overridden; that is, the method is locked to prevent the inherited class from changing it. final modifies a variable in a class, indicating that the variable cannot be changed once it is initialized.
The operating environment of this tutorial: windows7 system, java8 version, DELL G3 computer.
What is the final keyword?
1. Structures that final can be used to modify: classes, methods, variables
2. Final is used to modify a class: this class Cannot be inherited by other classes.
When we need to prevent a class from being inherited, we can use final modification, but please note: All member methods in the final class will be implicitly defined as final methods .
For example: String class, System class, StringBuffer class
3. Final is used to modify the method: indicating that this method cannot be overridden
- Function
(1) Lock the method to prevent the inherited class from changing it.
(2) Efficiency, in early Java versions, final methods will be converted into inline calls. However, if the method is too large, there may not be much improvement in performance. Therefore, in recent versions, final methods are no longer needed for these optimizations.
The final method means "final, final" meaning, that is, this method cannot be overridden.
For example: getClass( ) in the Object class
4. final is used to modify variables. At this time, the variable is equivalent to Constants
final is used to modify attributes: the locations that can be considered for assignment are: explicit initialization, initialization in code blocks, initialization in constructors
Final modified local variables: Especially when final is used to modify the formal parameter, it indicates that the formal parameter is a constant. When we call this method, we assign an actual parameter to the constant parameter. Once assigned, the value of this parameter can only be used in the method body and cannot be reassigned.
If final modifies a reference type, after initializing it, it can no longer point to other objects or its address cannot change (because the value of the reference is An address, final requires a value, that is, the value of the address does not change), but the content of the object pointed to by the reference can change. Essentially the same thing.
5. When using the final keyword to declare classes, variables and methods, you need to pay attention to the following points:
Use final In front of the variable, it means that the value of the variable cannot be changed. In this case, the variable can be called a constant.
final is used in front of a method to indicate that the method cannot be overridden (if a subclass creates a method with the same name, the same return value type, and the same parameter list as the parent class) , only the implementation in the method body is different to achieve functions different from those of the parent class. This method is called method rewriting, also known as method overwriting. Just understand it here, we will explain it in detail later in the tutorial).
final is used in front of a class to indicate that the class cannot have subclasses, that is, the class cannot be inherited.
final modified variable
The variable modified by final becomes a constant and can only be assigned a value once, but the variable modified by final There is a difference between local variables and member variables.
Final modified local variables must be assigned a value before they can be used.
Final modified member variables that are not assigned a value when declared are called "blank final variables". Empty final variables must be initialized in a constructor or static code block.
Note: It is wrong to say that a variable modified by final cannot be assigned a value. Strictly speaking, a variable modified by final cannot be changed. Once the initial value is obtained, the final variable The value cannot be reassigned.
public class FinalDemo { void doSomething() { // 沒有在聲明的同時(shí)賦值 final int e; // 只能賦值一次 e = 100; System.out.print(e); // 聲明的同時(shí)賦值 final int f = 200; } // 實(shí)例常量 final int a = 5; // 直接賦值 final int b; // 空白final變量 // 靜態(tài)常量 final static int c = 12;// 直接賦值 final static int d; // 空白final變量 // 靜態(tài)代碼塊 static { // 初始化靜態(tài)變量 d = 32; } // 構(gòu)造方法 FinalDemo() { // 初始化實(shí)例變量 b = 3; // 第二次賦值,會(huì)發(fā)生編譯錯(cuò)誤 // b = 4; } }
Lines 4 and 6 of the above code declare local constants. Line 4 just declares that there is no assignment, but it must be assigned before use (see line 6 of the code). In fact, it is best for local constants to be in Initialized at the same time as declaration. Lines 13, 14, 16, and 17 of the code all declare member constants. Lines 13 and 14 of the code are instance constants. If it is a blank final variable (see line 14 of the code), it needs to be initialized in the constructor (see line 27 of the code). Lines 16 and 17 of the code are static constants. If it is a blank final variable (see line 17 of the code), it needs to be initialized in a static code block (see line 21 of the code).
In addition, no matter what kind of constant, it can only be assigned once. See line 29 of the code for b constant assignment. Because b has been assigned once before, a compilation error will occur here.
The difference between final modified basic type variables and reference type variables
當(dāng)使用 final 修飾基本類型變量時(shí),不能對(duì)基本類型變量重新賦值,因此基本類型變量不能被改變。 但對(duì)于引用類型變量而言,它保存的僅僅是一個(gè)引用,final 只保證這個(gè)引用類型變量所引用的地址不會(huì)改變,即一直引用同一個(gè)對(duì)象,但這個(gè)對(duì)象完全可以發(fā)生改變。
下面程序示范了 final 修飾數(shù)組和 Person 對(duì)象的情形。
import java.util.Arrays; class Person { private int age; public Person() { } // 有參數(shù)的構(gòu)造器 public Person(int age) { this.age = age; } // 省略age的setter和getter方法 // age 的 setter 和 getter 方法 } public class FinalReferenceTest { public static void main(String[] args) { // final修飾數(shù)組變量,iArr是一個(gè)引用變量 final int[] iArr = { 5, 6, 12, 9 }; System.out.println(Arrays.toString(iArr)); // 對(duì)數(shù)組元素進(jìn)行排序,合法 Arrays.sort(iArr); System.out.println(Arrays.toString(iArr)); // 對(duì)數(shù)組元素賦值,合法 iArr[2] = -8; System.out.println(Arrays.toString(iArr)); // 下面語句對(duì)iArr重新賦值,非法 // iArr = null; // final修飾Person變量,p是一個(gè)引用變量 final Person p = new Person(45); // 改變Person對(duì)象的age實(shí)例變量,合法 p.setAge(23); System.out.println(p.getAge()); // 下面語句對(duì)P重新賦值,非法 // p = null; } }
從上面程序中可以看出,使用 final 修飾的引用類型變量不能被重新賦值,但可以改變引用類型變量所引用對(duì)象的內(nèi)容。例如上面 iArr 變量所引用的數(shù)組對(duì)象,final 修飾后的 iArr 變量不能被重新賦值,但 iArr 所引用數(shù)組的數(shù)組元素可以被改變。與此類似的是,p 變量也使用了 final 修飾,表明 p 變量不能被重新賦值,但 p 變量所引用 Person 對(duì)象的成員變量的值可以被改變。
注意:在使用 final 聲明變量時(shí),要求全部的字母大寫,如 SEX,這點(diǎn)在開發(fā)中是非常重要的。
如果一個(gè)程序中的變量使用 public static final 聲明,則此變量將稱為全局變量,如下面的代碼:
public static final String SEX= "女";
final修飾方法
final 修飾的方法不可被重寫,如果出于某些原因,不希望子類重寫父類的某個(gè)方法,則可以使用 final 修飾該方法。
Java 提供的 Object 類里就有一個(gè) final 方法 getClass(),因?yàn)?Java 不希望任何類重寫這個(gè)方法,所以使用 final 把這個(gè)方法密封起來。但對(duì)于該類提供的 toString() 和 equals() 方法,都允許子類重寫,因此沒有使用 final 修飾它們。
下面程序試圖重寫 final 方法,將會(huì)引發(fā)編譯錯(cuò)誤。
public class FinalMethodTest { public final void test() { } } class Sub extends FinalMethodTest { // 下面方法定義將出現(xiàn)編譯錯(cuò)誤,不能重寫final方法 public void test() { } }
上面程序中父類是 FinalMethodTest,該類里定義的 test() 方法是一個(gè) final 方法,如果其子類試圖重寫該方法,將會(huì)引發(fā)編譯錯(cuò)誤。
對(duì)于一個(gè) private 方法,因?yàn)樗鼉H在當(dāng)前類中可見,其子類無法訪問該方法,所以子類無法重寫該方法——如果子類中定義一個(gè)與父類 private 方法有相同方法名、相同形參列表、相同返回值類型的方法,也不是方法重寫,只是重新定義了一個(gè)新方法。因此,即使使用 final 修飾一個(gè) private 訪問權(quán)限的方法,依然可以在其子類中定義與該方法具有相同方法名、相同形參列表、相同返回值類型的方法。
下面程序示范了如何在子類中“重寫”父類的 private final 方法。
public class PrivateFinalMethodTest { private final void test() { } } class Sub extends PrivateFinalMethodTest { // 下面的方法定義不會(huì)出現(xiàn)問題 public void test() { } }
上面程序沒有任何問題,雖然子類和父類同樣包含了同名的 void test() 方法,但子類并不是重寫父類的方法,因此即使父類的 void test() 方法使用了 final 修飾,子類中依然可以定義 void test() 方法。
final 修飾的方法僅僅是不能被重寫,并不是不能被重載,因此下面程序完全沒有問題。
public class FinalOverload { // final 修飾的方法只是不能被重寫,完全可以被重載 public final void test(){} public final void test(String arg){} }
final修飾類
final 修飾的類不能被繼承。當(dāng)子類繼承父類時(shí),將可以訪問到父類內(nèi)部數(shù)據(jù),并可通過重寫父類方法來改變父類方法的實(shí)現(xiàn)細(xì)節(jié),這可能導(dǎo)致一些不安全的因素。為了保證某個(gè)類不可被繼承,則可以使用 final 修飾這個(gè)類。
下面代碼示范了 final 修飾的類不可被繼承。
final class SuperClass { } class SubClass extends SuperClass { //編譯錯(cuò)誤 }
因?yàn)?SuperClass 類是一個(gè) final 類,而 SubClass 試圖繼承 SuperClass 類,這將會(huì)引起編譯錯(cuò)誤。
final 修飾符使用總結(jié)
1. final 修飾類中的變量
表示該變量一旦被初始化便不可改變,這里不可改變的意思對(duì)基本類型變量來說是其值不可變,而對(duì)對(duì)象引用類型變量來說其引用不可再變。其初始化可以在兩個(gè)地方:一是其定義處,也就是說在 final 變量定義時(shí)直接給其賦值;二是在構(gòu)造方法中。這兩個(gè)地方只能選其一,要么在定義時(shí)給值,要么在構(gòu)造方法中給值,不能同時(shí)既在定義時(shí)賦值,又在構(gòu)造方法中賦予另外的值。
2. final 修飾類中的方法
說明這種方法提供的功能已經(jīng)滿足當(dāng)前要求,不需要進(jìn)行擴(kuò)展,并且也不允許任何從此類繼承的類來重寫這種方法,但是繼承仍然可以繼承這個(gè)方法,也就是說可以直接使用。在聲明類中,一個(gè) final 方法只被實(shí)現(xiàn)一次。
3. final 修飾類
表示該類是無法被任何其他類繼承的,意味著此類在一個(gè)繼承樹中是一個(gè)葉子類,并且此類的設(shè)計(jì)已被認(rèn)為很完美而不需要進(jìn)行修改或擴(kuò)展。
For members in final classes, you can define them as final or not. As for methods, since the class they belong to is final, they naturally become final. You can also explicitly add a final method to the final class, which is obviously meaningless.
Recommended tutorial: "java tutorial"
The above is the detailed content of What is the function of java final keyword. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used
