Java Fundamentals Analysis: final, Finally,finalize

Source: Internet
Author: User
Tags finally block

Final

final-modifier (keyword) If a class is declared final, it means that it can no longer derive a new subclass and cannot be inherited as a parent class. Therefore, a class cannot be declared abstract and declared final. Declaring variables or methods as final ensures that they are not changed in use. A variable declared as final must be given an initial value at the time of declaration, and can only be read in subsequent references and cannot be modified. A method that is declared final can also be used only and cannot be overloaded

Specific usage:

1. Finishing the final of the underlying data member

This is the primary purpose of final, which is modified as a constant, meaning it cannot be modified. As in the Java.lang.Math class, Pi and E are final members, with values of 3.141592653589793 and 2.718281828459045.

2. Final of the reference to the decorated class or object

In Java, we cannot let an object be decorated as final, but only a reference to the object, which means that even if you write public final A = new A (); In fact, the data of a point object can still be modified, and the reference value of a itself cannot be modified, that is, you can no longer re-assign a value to a.

3. Final of the modification method

First, the final meaning of the adornment method is not "non-modifiable", but the method cannot be redefined by the inherited member. (Note that what is said here cannot be redefined, not that the subclass must not define a method of the same name, if the parent class's method is a private type, the subclass is allowed to define the method, and here refers to the inability to redefine the method to make the method rewrite the polymorphism can be achieved, such as do not want a = new B (); A.F (); Such an overriding method occurs)

Example:

public class A {

Final method F

Public final void F () {

System.out.println ("Final method F in Class A is called");

}

}

public class B extends A {

Compile Error! The F method of the parent class is the final type and cannot be overridden!

//! public void F () {

//! System.out.println ("Method F in Class B is called");

//! }

}

In addition, when a method is decorated as a final method, it means that the compiler may load the method inline (inline), which means that the compiler does not invoke the method in a way that normally calls a function, but instead directly uses the code within the method to copy it into the original code by a certain modification ( Inserts a method body directly into the call, rather than making a method call. This allows the code to execute faster (because the cost of calling the function is omitted), such as int[] arr = new Int[3] Call Arr.length (), and so on.

on the other hand, private methods are implicitly decorated as final by the compiler, which means that private final void F () and private void F () are no different.

4. Final of the modified class

When a class is decorated as final, it has a clear meaning that the class is not allowed to be inherited, that is, the class is "unrepeatable", and any operations that inherit it will end up with a compilation error. (the member variable may not be final, the member method is final)

Example:

Public final class A {

}

Compile Error! A is the final type and cannot be inherited!

!public class B extends a{

//!}

5. Final parameter

Make final modifications to object parameters. The object variable is passed its reference, and is decorated to prevent unintentional changes during invocation.

————————————————————————————————————————————————————————————————————、

Finally

The finally keyword is the best complement to the Java exception handling model. The finally structure makes the code always executes, regardless of whether or not an exception occurs. Use finally to maintain the internal state of an object and to clean up non-memory resources. If you don't have a finally, your code will be confusing. For example, the following code illustrates how you must write code to free non-memory resources without using finally:

Import java.net.*;
Import java.io.*;

Class withoutfinally
{
public void Foo () throws IOException
{
Create a socket on any of the free ports
ServerSocket ss = new ServerSocket (0);
Try
{
Socket socket = ss.accept ();
The other code here ...
}
catch (IOException E)
{
Ss.close (); 1
Throw e;
}
//...
Ss.close (); 2
}
}

This code creates a socket and calls the Accept method. You must close this socket before exiting the method to avoid resource vulnerabilities. To complete this task, we call close at//2, which is the last statement of the method. But what happens if an exception occurs in a try block? In this case, the close call at//2 never occurs. Therefore, you must catch this exception and insert another call to close at//1 before you re-emit the exception. This will ensure that the socket is closed before exiting the method.

It is cumbersome and error-prone to write code, but it is essential in the absence of a finally. Unfortunately, in languages that do not have a finally mechanism, programmers may forget to organize their code in this way, leading to resource vulnerabilities. The finally clause in Java solves this problem. With finally, the preceding code can be rewritten in the following form:

Import java.net.*;
Import java.io.*;

Class withfinally
{
public void Foo2 () throws IOException
{
Create a socket on any of the free ports
ServerSocket ss = new ServerSocket (0);
Try
{
Socket socket = ss.accept ();
The other code here ...
}
Finally
{
Ss.close ();
}
}
}

The finally block ensures that the Close method is always executed, regardless of whether an exception is emitted within the try block. Therefore, you can ensure that the Close method is always called before exiting the method. This allows you to be confident that the socket is closed and that you are not leaking resources. There is no need for another catch block in this method. The catch block is provided in the first example just to close the socket, which is now closed by finally. If you do provide a catch block, the code in the finally block executes after the catch block finishes.

The finally block must be used in conjunction with a try or Try/catch block. In addition, it is not possible to exit the try block without executing its finally block. If a finally block exists, it is always executed. (from that point of view, the statement is correct.) There is a way to exit a try block without executing a finally block. If the code executes a system.exit (0) inside a try; Statement, the application terminates without performing a finally execution. On the other hand, finally will not execute if you unplug the power during the try block execution. )

Finalize

Garbage collector to reclaim objects, the first to call this class's Finalize method, the general Java-written class does not need to re-overwrite this method, because object has implemented a default, unless we want to implement a special function (which involves a lot of things, such as object space tree, etc.).
But with classes written outside of Java, the garbage collector does not recycle these parts properly, so we need to override the default method to implement proper release and recycling of this part of the memory (for example, C + + requires delete).
In summary, Finalize is equivalent to a destructor, which is the first method to be called when the garbage collector recycles an object. However, because Java's garbage collection mechanism can do these things for us automatically, we do not need to manually release them under normal circumstances.

Sometimes when you undo an object, you need to do something. For example, if an object is processing a non-Java resource, such as a file handle or a window character font, then you want to make sure that the resources are freed before an object is undone. To deal with this situation, Java provides a mechanism known as the closing (finalization). With this mechanism you can define special operations that are performed when an object is about to be released by the garbage collector.
To add the finishing touches to a class (finalizer), you just define the Finalize () method. This method is called when Java recycles an object of the class. In the Finalize () method, you specify the action that must be performed before an object is undone. Garbage collection runs periodically, checking that objects are no longer referenced by a running state or indirectly through other objects. Just before the object is freed, the Java runtime calls the Finalize () method of the object.

The general format of the Finalize () method is as follows:

protected void Finalize ()
{
Finalization code here
}

Where the keyword protected is to prevent code that is defined outside the class from accessing the Finalize () identifier. The identifier and other identifiers are explained in chapter 7th.

It is important to understand that finalize () is called just before garbage collection. For example, Finalize () is not called when an object is outside its scope. This means you can't know when--or even if--finalize () is called. Therefore, your program should provide other ways to release the system resources used by the object and not rely on finalize () to complete the normal operation of the program.

  


Finalize works like this: Once the garbage collector is ready to release the storage space occupied by the object, it calls Finalize () first, and the memory of the object is actually reclaimed only during the next garbage collection process. So if you use Finalize (), You can perform some important cleanup or cleaning work during garbage collection.

When was finalize () called?
There are three different cases
1. All objects are automatically called when garbage collection, such as when running System.GC ().
2. When the program exits, a finalize method is called for each object.
3. Explicitly call the Finalize method

Otherwise, when an object is collected by the system as useless information, Finalize () is automatically called, but the JVM does not guarantee that finalize () must be called, that is, the call to finalize () is indeterminate, This is why sun does not advocate the use of Finalize ()

Sometimes when you undo an object, you need to do something. For example, if an object is processing a non-Java resource, such as a file handle or a window character font, then you want to make sure that the resources are freed before an object is undone. To deal with this situation, Java provides a mechanism known as the closing (finalization). With this mechanism you can define special operations that are performed when an object is about to be released by the garbage collector.

To add the finishing touches to a class (finalizer), you just define the Finalize () method. This method is called when Java recycles an object of the class. In the Finalize () method, you specify the action that must be performed before an object is undone. Garbage collection runs periodically, checking that objects are no longer referenced by a running state or indirectly through other objects. Just before the object is freed, the Java runtime calls the Finalize () method of the object.

The general format of the Finalize () method is as follows:

protected void Finalize ()
{
Finalization code here
}

Where the keyword protected is to prevent code that is defined outside the class from accessing the Finalize () identifier. The identifier and other identifiers are explained in chapter 7th.

It is important to understand that finalize () is called just before garbage collection. For example, Finalize () is not called when an object is outside its scope. This means you can't know when--or even if--finalize () is called. Therefore, your program should provide other ways to release the system resources used by the object and not rely on finalize () to complete the normal operation of the program.

Note: If you are familiar with C + +, you know that C + + allows you to define an undo function (destructor) for a class that is called before the object is out of scope. Java does not support this idea nor does it provide undo functions. The Finalize () method is only close to the function of the undo function. When you have a lot of experience with Java, you will see that because Java uses the garbage collection subsystem, there is little need to use undo functions.

The garbage collector automatically calls the Finalize method of the object when it is garbage collected, for some user-defined non-memory cleanup work, because the garbage collector does not handle anything other than memory. So, sometimes users need to define some cleanup methods, such as handling non-memory resources such as files and ports.

Java Fundamentals Analysis: final, Finally,finalize

Related Article

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.