the difference between final,finalize and finally in Java FinalThe final keyword can be used for classes, methods, and variables that represent the class to which the keyword is decorated, methods, and variables that have immutable properties. (1) The final keyword is used before the base data type: This means that the variable that the keyword modifies is a constant, and the value of the variable cannot be modified after it is defined. (2) The final keyword is used before the method declaration: This means the final method, which can only be invoked, cannot be overwritten, but can be overloaded. (3) The final keyword is used before the class name: At this point the class is called the final class and the class cannot be inherited by other classes.
for (1):
For (2):
For (3):
FinalizeThe Finalize method is derived from Java.lang.Object and is used to reclaim resources. You can add a finalize method to any class. The Finalize method is called before the garbage collector clears the object. In practice, do not rely on using this method to reclaim any shortage of resources, because it is difficult to know when this method is invoked.
<span style= "FONT-SIZE:14PX;" >class people{
final void output (String name) {
System.out.println (name);
}
}
Class Stu extends people{
final void output (String name,int ID) {//Can be overloaded
System.out.println (name);
}
public void Finalize () throws throwable{
super.finalize ();
System.out.println ("Finalize method is called!");
}
public class Main {public
static void Main (string[] args) {
}
}</span>
finallyWhen the code throws an exception, it terminates the processing of the remaining code in the method and exits the execution of the method. If we open a file, but an exception occurs during the processing of the file, the file is not closed, and a resource recycle problem arises. In this case, Java provides a good solution, that is the finally clause, the FINALLY clause in the statement is bound to be executed, so we simply put the previous statement of the file closed in the finally clause, regardless of whether in the read-write file encountered an exception exit, File closing statements are executed to ensure a reasonable recovery of resources.
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import java.io.IOException;
Import Java.io.InputStream;
public class Finally {
void Filewith () {
inputstream in = null;
try {in
= new FileInputStream ("Wang.txt");
Other Operations
} catch (FileNotFoundException e) {
e.printstacktrace ();
} finally{
try {
in.close ();
} catch (IOException e) {
e.printstacktrace ();
}
}}}