Usage of final, finalized, finally, and static

Source: Internet
Author: User
Tags finally block

 

Final:
Final allows you to control whether your members, methods, or a class can be overwritten or inherited. These features make final an indispensable role in Java, it is also one of the keywords that must be known and mastered when learning Java.
Final member
When you define a variable in a class and add the final keyword before it, this variable cannot be changed once initialized, the unchangeable meaning here is that its value is immutable for the basic type, and its reference for the object variable cannot be changed. It can be initialized in two places, one is its definition, and the other is in the constructor, the two can only choose one.
The following program demonstrates the general usage of final:
Public class test {
Final int T = 1; // value given during definition
// Or (either)
Final int T;
Public test (){
T = 3; // value given during construction
}
}

Another method is to define the final parameter in the method. For variables of the basic type, this method has no practical significance, because the variables of the basic type are passed values when calling the method, that is to say, you can change this parameter variable in the method without affecting the call statement. However, it is very practical for the object variable because the object variable is passed with its reference during transmission, in this way, your modification to the object variable in the method will also affect the object variable in the call statement. When you do not need to change the object variable used as the parameter in the method, use final to declare it, it will prevent you from accidentally modifying the call method.
In addition, when the internal class in the method uses the variable in the method, this parameter must be declared as final for use, as shown in the following code:
Public class test {
Void print (final string Str ){
Class innertest {
Innertest (){
System. Out. println (STR );
}
}
Innertest it = new innertest ();
}
Public static void main (string [] ARGs ){
Test test = new test ();
Test. Print ("Hello word !!! ");
}
}
Final Method
There are two reasons to declare the method as final. The first is that you know that the function provided by this method has met your requirements and does not need to be extended, this method cannot be overwritten by any class inherited from this class, but inheritance can still inherit this method, that is, it can be used directly. The second is to allow the compiler to convert all calls to this method into an inline (in-line) Call mechanism, which will allow you to directly Insert the method subject to the call when calling the final method, instead of making routine method calls, such as saving breakpoints and pushing stacks, this may improve the efficiency of your program. However, when your method subject is very large, or if you call this method in multiple places, your calling subject code will expand rapidly, which may affect the efficiency. Therefore, you must use final for method definition with caution.
Final class
When using final on a class, you need to consider it carefully. Because a final class cannot be inherited by anyone, it means that this class is a leaf class in an inheritance tree, in addition, such designs have been considered perfect without modification or expansion. For members in the final class, you can define it as final or not final. For methods, because the class is final, they naturally become final. You can also explicitly add a final to the methods in the final class, but this is obviously meaningless.

Finally:
The finally keyword is the best supplement to the Java Exception Handling Model. The finally structure enables code to always be executed, regardless of exceptions. Using Finally, you can maintain the internal status of an object and clear non-memory resources. Without finally, your code will be hard to understand. For example, the following code describes how to write code to release non-memory resources without using finally:

Public void writefile (string filepath, string filename, string ARGs)
Throws ioexception

{

Filewriter fw = new filewriter (filepath + filename );
Try {

FW. Write (ARGs );
} Catch (ioexception e ){
// 1
FW. Close ();
Throw E;
}
// 2
FW. Close ();
}
This Code creates a filewriter object and calls the write method. Before exiting this method, you must disable filewriter object to avoid resource vulnerabilities. To complete this task, we call close at // 2, which is the last statement of the method. However, what if an exception occurs in the try block? In this case, the close call at // 2 will never happen. Therefore, you must capture this exception and insert another call to close at // 1 before sending the exception again. In this way, you can disable filewriter object before exiting this method. Writing code in this way is both troublesome and error-prone, but it is essential without finally. With Finally, the previous code can be rewritten as follows:

Public void writefile (string filepath, string filename, string ARGs)
Throws ioexception

{

Filewriter fw = new filewriter (filepath + filename );
Try {

FW. Write (ARGs );
} Catch (ioexception e ){
Throw E;
} Finally {

FW. Close ();
}
}
The finally block ensures that the close method is always executed, regardless of whether an exception occurs in the try block. Therefore, you can ensure that the close method is always called before exiting this method. In this way, you can be sure that the filewriter object is closed and you have not leaked the resource.

Finalize:

According to the Java language specification, the JVM ensures that the object is reachable before the finalize function is called, but the JVM does not guarantee that the function will be called. In addition, the finalize function can run at most once.

In general, finalize is used to release very important resources that are not easily controlled, such as I/O operations and data connections. The release of these resources is critical to the entire application. In this case, programmers should primarily manage (including release) these resources through the program itself, supplemented by the finalize function to release resources, to form a double-insurance management mechanism, instead of relying solely on finalize to release resources.
Final keyword and static usage

I. Final
According to the context of the program, the Java keyword final has the meaning of "This cannot be changed" or "final state". It can modify non-abstract classes, non-abstract class member methods, and variables. You may need to block changes in two ways: design or efficiency.

The final class cannot be inherited and has no subclass. The methods in the final class are final by default.
The final method cannot be overwritten by the quilt class, but can be inherited.
Final member variables indicate constants and can only be assigned once. The values do not change after the values are assigned.
Final cannot be used to modify the constructor.
Note: The Private member method of the parent class cannot be overwritten by the quilt class method. Therefore, the private type method is of the final type by default.

1. Final class
The final class cannot be inherited. Therefore, the member methods of the final class have no chance to be overwritten. By default, they are all final. When designing a class, if this class does not need a subclass, the implementation of the class

The details cannot be changed and are sure that this class will not be loaded and extended, so it is designed as a final class.

2. Final Method
If a class does not allow its subclass to overwrite a method, you can declare this method as a final method.
There are two reasons for using the final method:
First, lock the method to prevent any inheritance class from modifying its meaning and implementation.
Second, efficient. The compiler transfers the final method to the embedded mechanism to greatly improve the execution efficiency.
For example:

 

Public class test1 {

Public static void main (string [] ARGs ){
// Todo automatically generates method stubs
}

Public void F1 (){
System. Out. println ("f1 ");
}
// Method that cannot be overwritten by a quilt
Public final void F2 (){
System. Out. println ("F2 ");
}

Public void F3 (){
System. Out. println ("F3 ");
}

Private void F4 (){
System. Out. println ("F4 ");
}
}

Public class Test2 extends test1 {

Public void F1 (){
System. Out. println ("test1 parent class method F1 is overwritten! ");
}

Public static void main (string [] ARGs ){
Test2 T = new Test2 ();
T. F1 ();
T. F2 (); // call the final method inherited from the parent class
T. F3 (); // call the method inherited from the parent class
// T. F4 (); // The call fails and cannot be obtained from the parent class.

}
}

3. Final variable (constant)
The final modified member variable is used to represent constants. Once given, the value cannot be changed!
Three final-modified variables are available: static variables, instance variables, and local variables, representing three types of constants respectively.
As shown in the following example, the final variable value cannot be changed once it is given.
In addition, when final variables are defined, they can be declared first without initial values. In this case, variables are also called final blank, no matter what the situation is, the compiler ensures that the blank final must be initialized before use. However, the final blank space provides greater flexibility in the use of the final keyword final. For this reason, the final data members in a class can be implemented based on objects, but there are features that keep them unchanged.

 

Package org. leizhimin;

Public class test3 {
Private final string S = "final instance variable s ";
Private Final int A = 100;
Public final int B = 90;

Public static final int c = 80;
Private Static final int d = 70;

Public final int e; // blank final. The initial value must be assigned when the object is initialized.

Public test3 (int x ){
E = X;
}

/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
Test3 T = new test3 (2 );
// T. A = 101; // error. The final variable value cannot be changed once it is specified.
// T. B = 91; // error. The final variable value cannot be changed once given.
// T. C = 81; // error. The final variable value cannot be changed once it is specified.
// T. D = 71; // error. The final variable value cannot be changed once it is specified.

System. Out. println (T. );
System. Out. println (T. B );
System. Out. println (T. C); // It is not recommended to access static fields using objects.
System. Out. println (T. D); // It is not recommended to access static fields using objects.
System. Out. println (test3.c );
System. Out. println (test3.d );
// System. Out. println (test3.e); // error. Because E is blank in final, it varies according to different object values.
System. Out. println (T. E );

Test3 T1 = new test3 (3 );
System. Out. println (t1.e); // The final blank variable e varies depending on the object
}

Private void test (){
System. Out. println (New test3 (1). );
System. Out. println (test3.c );
System. Out. println (test3.d );
}

Public void Test2 (){
Final int A; // blank final, assigned only when needed
Final int B = 4; // local constant -- Final is used for local variables.
Final int C; // The final is blank and has not been assigned a value.
A = 3;
// A = 4; error. The value has been assigned.
// B = 2; error. The value has been assigned.
}
}

 
4. Final Parameters
When the function parameter is of the final type, you can read and use this parameter, but you cannot change the value of this parameter.

 

Public class test4 {
Public static void main (string [] ARGs ){
New test4 (). F1 (2 );
}

Public void F1 (final int I ){
// I ++; // I is of the final type and cannot be changed.
System. Out. Print (I );
}
}

Ii. Static

Static indicates the meaning of "global" or "static". It is used to modify member variables and member methods. It can also form static code blocks, but Java does not have the concept of global variables.
The static modified member variables and member methods are independent of any object in the class. That is to say, it is shared by all instances of the class and does not depend on a specific instance of the class. As long as the class is loaded, the Java Virtual Machine can locate the class names in the Method Area of the runtime data zone. Therefore, a static object can be accessed before any of its objects are created without referencing any objects.

Static member variables and member Methods Modified with public are essentially global variables and global methods. When the object city of the declared class does not generate a copy of static variables, instead, all instances of the class share the same static variable.

The static variable can be modified in private, indicating that the variable can be in the static code block of the class, or other static member methods of the class (you can also use -- nonsense in non-static member methods), but it cannot be directly referenced by the class name in other classes, this is important. In fact, you need to understand that private is the access permission limitation, and static means that it can be used without instantiation, so that it is much easier to understand. The effect of adding other access key words before static is also similar.

Static modified member variables and member methods are usually called static variables and static methods. They can be accessed directly by class names. The access syntax is as follows:
Class Name. Static Method Name (parameter list ...)
Class Name. static variable name

A static code block is a static code block. When a Java Virtual Machine (JVM) loads a class, the code block is executed (very useful ).

1. Static variables
Class member variables can be classified by static or not. One is static modified variables, such as static variables or class variables; the other is a variable that is not modified by static, called an instance variable. The difference between the two is:
For static variables that only have one copy (memory saving) in the memory, JVM only allocates the memory for the static one time, and completes the memory allocation of the static variables during the loading process, you can directly access the available class name (convenient). Of course, you can also access it through an object (but this is not recommended ).
If an instance variable is not created, the instance variable will be allocated with memory once. The instance variables can be copied multiple times in the memory without affecting each other (flexible ).

2. Static Method
Static methods can be called directly through the class name, and can be called by any instance. Therefore, this and super keywords cannot be used in static methods, you cannot directly access the instance variables and instance methods of the class (that is, the static member variables and member methods are not included). You can only access static member variables and member methods of the class. Because instance members are associated with specific objects! You need to understand the truth, not the memory !!!
Because the static method is independent of any instance, the static method must be implemented rather than abstract.

3. Static code block
A static code block is also called a static code block. It is a static statement Block Independent of class members in a class. It can have multiple static code blocks and can be placed anywhere. It is not in any method body, when a JVM loads a class, it executes these static code blocks. If there are multiple static code blocks, the JVM executes them in sequence according to the sequence they appear in the class, and each code block is executed only once. For example:

 

Public class test5 {
Private Static int;
Private int B;

Static {
Test5.a = 3;
System. Out. println ();
Test5 T = new test5 ();
T. F ();
T. B = 1000;
System. Out. println (T. B );
}
Static {
Test5.a = 4;
System. Out. println ();
}
Public static void main (string [] ARGs ){
// Todo automatically generates method stubs
}
Static {
Test5.a = 5;
System. Out. println ();
}
Public void F (){
System. Out. println ("hhahhahah ");
}
}

 

Running result:
3
Hhahhahah
1000
4
5

Static code blocks can be used to assign values to some static variables. In the end, these examples all use a static main method, so that the JVM can directly call the main method without creating an instance.

4. What does static and final use to represent?
Static final is used to modify member variables and member methods. It can be simply understood as a "global constant "!
For a variable, it means that once the value is given, it cannot be modified and can be accessed through the class name.
For methods, it means they cannot be overwritten and can be accessed directly by class names.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.