本文介绍了Java中的final关键字,finally块和finalized方法之间的区别是一个很好的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些关键字常常使我感到困惑.

Often these keywords confuse me.

谁能准确告诉我他们之间的区别?

Can any one tell me exactly what the difference between them is?

推荐答案

最终关键字

课程

在课堂上,这意味着您禁止开设子课程来扩展您的课程.

On a class it means you forbid to have a child class extending yours.

public final class finalClass

属性/字段

final MyObject value = new MyObject()表示您将无法修改该对象的实例.

final MyObject value = new MyObject() means you won't be able to modify the instance of the object.

value = xxxx将不被允许,但是您仍然可以修改对象本身value.field = "xxx";

value = xxxx won't be allowed, but you still can modify the object itself value.field = "xxx";

方法在方法上使用final时,这意味着您将禁止扩展该类的子类以覆盖此方法.

MethodWhen you use final on a method, that means you'll forbid child classes that extends your class to override this method.

public final void finalMethod()

它也可以用于参数,这意味着您不允许其他人修改您提供的对象的实例.

It can also be used on arguments, that means you don't allow other to modify the instance of the object you give.

public void myMethod(final MyObject myObject)

最终用户将无法执行myObject = ...

finally块与final无关,用于捕获Exception以确保无论是否存在异常,都将运行部分代码.

finally block has nothing to do with final, it's used when catching Exception to ensure a part of code will be ran, wherever there is an exception or not.

try { ...}
catch {} // Optional
finally { // Code that will be ran, exception or not being thrown}

销毁每个对象(通常是垃圾收集)时会调用它.

It's called on every object when it's destroyed (usually garbage collected).

这篇关于Java中的final关键字,finally块和finalized方法之间的区别是一个很好的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 03:55