final、finally 和 finalize 在 Java 中
final 关键字可与类方法和变量一起使用。不能继承 final 类,不能覆盖 final 方法,不能重新赋值 final 变量。
finally 关键字用来创建紧跟 try 代码块的一个代码块。无论是否发生异常,finally 代码块都会始终执行。使用 finally 代码块可运行你希望执行的任何清理类型陈述,无论在受保护的代码中发生了什么。
finalize() 方法在销毁对象前使用,可以在对象创建前调用。
final 示例
public class Tester {
final int value = 10;
// The following are examples of declaring constants:
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
finally 示例
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.
finalize 示例
public class Tester {
public void finalize() throws Throwable{
System.out.println("Object garbage collected.");
}
public static void main(String[] args) {
Tester t = new Tester();
t = null;
System.gc();
}
}输出
Object garbage collected.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP