的最终关键字可与类方法和变量被使用。不能实例化final类,不能覆盖final方法,并且不能重新分配final变量。
在最后关键字用于创建遵循try块的代码块。无论是否发生异常,最终代码块总是执行。尽管受保护的代码中发生了什么,但使用finally块可以使您运行您只想执行的任何清理类型的语句。
的最终化()方法被用于之前对象被销毁,并且可以被称为刚刚之前对象的创建。
public class Tester {
final int value = 10;
//以下是声明常量的示例:
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";
public void changeValue() {
value = 12; // will give an error
}
public void displayValue(){
System.out.println(value);
}
public static void main(String[] args) {
Tester t = new Tester();
t.changeValue();
t.displayValue();
}
}输出结果
编译器将在编译过程中引发错误。
Tester.java:9: error: cannot assign a value to final variable value value = 12; // will give an error ^ 1 error
public class Tester {
public static void main(String[] args) {
try{
int a = 10;
int b = 0;
int result = a/b;
}catch(Exception e){
System.out.println("Error: "+ e.getMessage());
}
finally{
System.out.println("Finished.");
}
}
}输出结果
Error: / by zero Finished.
public class Tester {
public void finalize() throws Throwable{
System.out.println("收集对象垃圾。");
}
public static void main(String[] args) {
Tester t = new Tester();
t = null;
System.gc();
}
}输出结果
收集对象垃圾。