本文介绍了在Java中,关键字`final`,`finally`和`finalize`的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,关键字finalfinallyfinalize的用途是什么?

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`的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 00:45