在Java中,关键字`final`,`finally`和`finalize`的作用是什么? [英] In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?
问题描述
在Java中,关键字final
,finally
和finalize
的用途是什么?
In Java, what purpose do the keywords final
, finally
and finalize
fulfil?
推荐答案
最终
final
可用于将变量标记为不可更改"
final
final
can be used to mark a variable "unchangeable"
private final String name = "foo"; //the reference name can never change
final
也可以使方法不可重写"
final
can also make a method not "overrideable"
public final String toString() { return "NULL"; }
final
也可以使一个类不是可继承的".即该类不能被子类化.
final
can also make a class not "inheritable". i.e. the class can not be subclassed.
public final class finalClass {...}
public class classNotAllowed extends finalClass {...} // Not allowed
最终
finally
在try/catch语句中用于始终"执行代码
finally
finally
is used in a try/catch statement to execute code "always"
lock.lock();
try {
//do stuff
} catch (SomeException se) {
//handle se
} finally {
lock.unlock(); //always executed, even if Exception or Error or se
}
Java 7具有一个新的资源尝试语句,您可以使用它自动关闭显式或隐式实现 java.io.Closeable 或 java.lang.AutoCloseable
Java 7 has a new try with resources statement that you can use to automatically close resources that explicitly or implicitly implement java.io.Closeable or java.lang.AutoCloseable
finalize
.您很少需要覆盖它.一个例子:
finalize
is called when an object is garbage collected. You rarely need to override it. An example:
protected void finalize() {
//free resources (e.g. unallocate memory)
super.finalize();
}
这篇关于在Java中,关键字`final`,`finally`和`finalize`的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!