JAVA Face Question FAQ series –final, finally and finalize difference __java

Source: Internet
Author: User
Tags modifier throwable
This is a classic interview question, we can almost see it in the interview questions of various companies.
Final, finally, and finalize, though they look like the twin brothers, their meanings and usages are quite different.
This time we will come together to review this knowledge.
Final key word
Let's say final in the first place. It can be used in the following four places:
1. Define variables, both static and non-static.
2. Define the parameters of the method.
3. Define methods.
4. Define class.
Let's take a look at the final role in each case in turn. First of all, look at the first case, if the final modifier is a basic type, it means that the value assigned to the variable is immutable, that is, that it is a constant, and that if the final modifier is an object, it means that the reference to the variable is immutable, and here we need to remind you that What is immutable is only the reference that is saved by this variable, not the object that the reference refers to. In the second case, final has the same meaning as the first. In fact, for the first two cases, there is a more appropriate description of the final meaning, that is, if a variable or method parameter is final decorated, it means that it can only be assigned once, but the default value set by the Java Virtual machine for the variable is not recorded as an assignment.
The final modified variable must be initialized. There are several ways to initialize the following:
1. Initialize at the time of definition.
2. Final variables can be initialized in the initialization block and cannot be initialized in static initialization blocks.
3. Static final variables can be initialized in a static initialization block and cannot be initialized in an initialization block.
4. The final variable can also be initialized in the constructor of the class, but the static final variable is not available.
The following code can be used to verify the above view:
Java code
public class Finaltest {
Class at the time of the definition
public final int A = 10;
public final int B;
Class in the initialization block.
{
B = 20;
}
Non-__________ static final variable cannot be initialized in a static initialization block
public final int C;
static {
C = 30;
// }
Static constants, initialized at definition
public static final int static_d = 40;
public static final int static_e;
Static constants, initialized in a static initialization block
static {
Static_e = 50;
}
Static variables cannot be initialized in the initialization block
public static final int static_f;
// {
Static_f = 60;
// }
public final int G;
Static final variables cannot be initialized in constructors
public static final int static_h;
Class in the constructor.
Public Finaltest () {
G = 70;
Static final variables cannot be initialized in constructors
Static_h = 80;
When the final variable is assigned a second time, the compilation will give an error
A = 99;
Static_d = 99;
}
Final variable not initialized, error occurs at compile time
public final int I;
The static final variable is not initialized and an error occurs at compile time
public static final int static_j;
}
When we run the above code, we can find that final variables (constants) and static final variables (static constants) are not initialized, and the compilation will complain.
The final-modified variables (constants) are more efficient than the final variables (ordinary variables), so we should use as many constants as possible instead of ordinary variables in actual programming, which is also a good programming practice.
What happens when final is used to define a method? As you know, it means that this method cannot be overridden by a quilt, but it does not affect its quilt class inheritance. Let's write a piece of code to verify:
Java code
Class ParentClass {
Public final void Testfinal () {
System.out.println ("Parent class – This is a final method");
}
}
public class Subclass extends ParentClass {
/**
* Subclasses cannot override the final method of the (override) parent class, otherwise the error occurs at compile time
*/
public void Testfinal () {
System.out.println ("Subclass – Rewrite Final method");
// }
public static void Main (string[] args) {
Subclass SC = new subclass ();
Sc. Testfinal ();
}
}
The special note here is that a method with private access can also increase the final decoration, but it cannot be overridden because the subclass cannot inherit the private method. The compiler treats the private method with the final method, which increases the efficiency of the method when it is invoked. However, subclasses can still define methods with the same structure as private methods in the half, but this does not produce the effect of rewriting, and there is no inevitable connection between them.
Finally, let's review the final use of the class. This should be familiar to everyone, because our most common string class is final. Since the final class is not allowed to be inherited, the compiler treats all its methods as final, so that final analogy to the general class has higher efficiency. Abstract classes defined by keyword Abstract contain abstract methods that must be implemented by inheriting from its subclass, so the same class cannot be decorated with final and abstract at the same time.
In the same way, final can not be used to modify interfaces. None of the methods of the final class can be overridden, but this does not mean that the final class's property (variable) value is immutable, and if you want to make the final class property value immutable, you must add final modification to it, see the following example:
Java code
Public final class Finaltest {
int i = 10;
public static void Main (string[] args) {
Finaltest ft = new Finaltest ();
FT.I = 99;
System.out.println (FT.I);
}
}
Try to run the code above, and the result is 99, not 10 when initialized.
Finally statement
Let's review the finally usage together. This is relatively simple, it can only be used in the Try/catch statement,
And is accompanied by a statement block, which means that the statement is always executed at all time. Take a look at the following code:
Java code
Public final class Finallytest {
public static void Main (string[] args) {
try {
throw new NullPointerException ();
catch (NullPointerException e) {
System.out.println ("program throws an exception");
finally {
System.out.println ("execute a finally statement block");
}
}
}
The results of the operation illustrate the effect of finally:
1. The program throws an exception
2. A finally statement block was executed
Please note that after catching the exception thrown by the program, neither processing, nor continue to throw up the exception, is not good programming habits, it covers the implementation of the program error occurred, here is only convenient demo, please do not learn.
So is there a situation where the finally statement block is not executed? You may have thought of it.
Return, continue, break these three can disrupt the code sequence to execute the rules of the statement. So let's try to see if these three statements can affect the execution of the finally statement block:
Java code
Public final class Finallytest {
Test Return statement
Public Returnclass Testreturn () {
try {
return new Returnclass ();
catch (Exception e) {
E.printstacktrace ();
finally {
SYSTEM.OUT.PRINTLN ("Execute finally Statement");
}
return null;
}
To test the Continue statement
public void Testcontinue () {
for (int i = 0; i < 3; i++) {
try {
System.out.println (i);
if (i = = 1) {
Continue
}
catch (Exception e) {
E.printstacktrace ();
finally {
SYSTEM.OUT.PRINTLN ("Execute finally Statement");
}
}
}
Test break statement
public void Testbreak () {
for (int i = 0; i < 3; i++) {
try {
System.out.println (i);
if (i = = 1) {
Break
}
catch (Exception e) {
E.printstacktrace ();
finally {
SYSTEM.OUT.PRINTLN ("Execute finally Statement");
}
}
}
public static void Main (string[] args) {
Finallytest ft = new Finallytest ();
Test Return statement
Ft.testreturn ();
System.out.println ();
To test the Continue statement
Ft.testcontinue ();
System.out.println ();
Test break statement
Ft.testbreak ();
}
}
Class Returnclass {
Public Returnclass () {
System.out.println ("Execute return statement");
}
}
The results of the above code are as follows:
1. Execution of Return statement
2. The finally statement was executed
3.
4.0
5. The finally statement was executed
6.1
7. The finally statement was executed
8.2
9. The finally statement was executed
10.
11.0
12. The finally statement was executed
13.1
14. The finally statement was executed
Obviously, return, continue, and break do not block the execution of the finally statement block. As a result of the output, the return statement seems to have been executed before the finally statement block. Let's see, what's the function of the return statement? is to exit the current method, returning the value or object. If the finally statement block is executed after the return statement, then the return statement is executed and the current method is exited, and how can a finally statement block be executed? So the correct order of execution should be this: The compiler is compiling return new Returnclass (), when it is divided into two steps, new Returnclass () and return, the previous statement that created the object was executed before the finally statement block, and the last return statement was executed after the finally statement block. This means that the finally statement block is executed before the program exits the method. Similarly, a finally statement block is executed before the loop is skipped (continue) and interrupted (break).
Finalize method
Finally, let's look at Finalize, which is a method, belonging to the Java.lang.Object class, which is defined as follows:
Java code
protected void Finalize () throws Throwable {}
As we all know, the Finalize () method is part of the GC (garbage collector) operating mechanism, and the knowledge about GC we
will be reviewed in subsequent chapters.
Here we just say what the Finalize () method does?
The Finalize () method is invoked when the GC cleans up objects it is subordinate to. If an unhandled exception (Uncaught exception) is thrown during execution, the GC terminates cleanup of the modified object and the exception is ignored until the next GC begins to clean the object. Its finalize () is called again.
Take a look at the following example:
Java code
Public final class Finallytest {
Rewrite the Finalize () method
protected void Finalize () throws Throwable {
System.out.println ("Execute Finalize () method");
}
public static void Main (string[] args) {
Finallytest ft = new Finallytest ();
FT = null;
System.GC ();
}
}
The results of the operation are as follows:
• Implementation of Finalize () method
The program invokes the GC () method of the Java.lang.System class, which causes the GC to execute, and the GC calls its finalize () method when the FT object is cleaned up, so that the output above is obtained. Calling System.GC () is equivalent to calling the following line of code:
Java code
Runtime.getruntime (). GC ();
The effect of calling them is only to recommend that the garbage collector (GC) boot up, clean up unused objects to free up memory space, but the GC startup is not certain, which is determined by the Java virtual machine. Until the Java virtual machine stops running and some of the objects ' finalize () may not have been run, how do you guarantee that this method of all objects must be invoked before the Java virtual machine stops running? The answer is another way we can invoke the System class:
Java code
public static void Runfinalizersonexit (Boolean value) {
Other code
}
Passing true to this method guarantees that the object's finalize () method must be run before the Java virtual machine stops running, but unfortunately this method is unsafe and causes the useful object Finalize () to be invoked incorrectly and is therefore not approved for use.
Because Finalize () belongs to the object class, all classes have this method, and any subclass of object can override (override) The method, freeing system resources or doing other cleanup work, such as turning off the input and output stream.
Through the review of the above knowledge, I think we are very clear about final, finally, finalize the usage difference.

Interview manual from IT company

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.