java中final关键字、finally块和finalized方法的区别举一个很好的例子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27815947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:06:09  来源:igfitidea点击:

Difference between final keyword, finally block and finalized method in java throught one good example

javafinalfinallyfinalize

提问by Mitul Maheshwari

Often these keywords confuse me.

这些关键词常常让我感到困惑。

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

谁能告诉我他们到底有什么区别?

回答by Michael Laffargue

final keyword

最终关键字

class

班级

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

在课堂上,这意味着您禁止让子课程扩展您的课程。

public final class finalClass

Attribute/Field

属性/字段

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

final MyObject value = new MyObject()意味着您将无法修改对象的实例。

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

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

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

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

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)

The end user won't be able to do myObject = ...

最终用户将无法做到 myObject = ...



Finally block

最后阻止

finallyblock 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.

finallyblock 与 无关final,它在捕获异常时使用,以确保无论是否有异常都会运行一部分代码。

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

Finally in Java

终于在Java中



Finalize method

完成方法

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

当它被销毁(通常是垃圾收集)时,它会在每个对象上调用。

回答by atish shimpi

The java Final keywordcan be used in many context.

java Final 关键字可以在许多上下文中使用。

  1. Variable - If you make any variable as final, you cannot change the value of final variable(It will be constant).
  2. Method - If you make any method as final, you cannot override it.
  3. Class - If you make any class as final, you cannot extend it. read more
  1. 变量 - 如果将任何变量设置为 final,则无法更改 final 变量的值(它将是常量)。
  2. 方法 - 如果您将任何方法设为最终方法,则无法覆盖它。
  3. 类 - 如果您将任何类设为最终类,则无法扩展它。 阅读更多

The finally Block

最后的块

The finallyblock always executes when the tryblock exits. This ensures that the finallyblock is executed even if an unexpected exception occurs. Putting cleanup codein a finallyblock is always a good practice, even when no exceptions are anticipated. read more

finally块始终执行时try块退出。这确保finally即使发生意外异常也能执行该块。将清理代码放在一个finally块中始终是一个好习惯,即使没有预料到异常也是如此。阅读更多

finalize methodin java is a special methodmuch like main method in java. finalize()is called before Garbage collectorreclaim the Object, its last chance for any object to perform cleanup activity

java中的finalize方法是一种特殊的方法,很像java中的main方法。在垃圾收集器回收对象之前finalize()调用,这是任何对象执行清理活动的最后机会

Main issue with finalizemethod in java is its not guaranteed by JLS that it will be called by Garbage collector or exactly when it will be called, for example an object may wait indefinitely after becoming eligible for garbage collection and before its finalize()method gets called. similarly even after finalize gets called its not guaranteed it will be immediately collected. read more

finalizeJava 中的方法的主要问题是JLS 不保证它会被垃圾收集器调用或确切地何时被调用,例如,一个对象可能会在成为垃圾收集资格后和它的finalize()方法被调用之前无限期地等待。同样,即使在 finalize 被调用后,也不能保证它会立即被收集。阅读更多

回答by Abhishek

Final:-It is used in the following cases:

Final:-它用于以下情况:

  • If the final keyword is attached to a variable then the variable becomes constant i.e. its value cannot be changed in the program.
  • If a method is marked as final then the method cannot be overridden by any other method.
  • If a class is marked as final then this class cannot be inherited by any other class.
  • If a parameter is marked with final it becomes a read only parameter.
  • 如果 final 关键字被附加到一个变量上,那么这个变量就变成了常量,即它的值不能在程序中改变。
  • 如果一个方法被标记为 final,则该方法不能被任何其他方法覆盖。
  • 如果一个类被标记为 final,那么这个类不能被任何其他类继承。
  • 如果一个参数被标记为 final,它就成为一个只读参数。

Finally:-

Finally:-

If an exception is thrown in try block then the control directly passes to the catch block without executing the lines of code written in the remainder section of the try block. In case of an exception we may need to clean up some objects that we created. If we do the clean-up in try block, they may not be executed in case of an exception. Thus finally block is used which contains the code for clean-up and is always executed after the try ...catch block.

如果在 try 块中抛出异常,则控制直接传递到 catch 块,而不执行在 try 块的剩余部分中编写的代码行。如果出现异常,我们可能需要清理一些我们创建的对象。如果我们在 try 块中进行清理,则在出现异常时可能不会执行它们。因此使用 finally 块,它包含用于清理的代码并且总是在 try ...catch 块之后执行。

Finalize:-

Finalize:-

It is a method present in a class which is called before any of its object is reclaimed by the garbage collector. finalize()method is used for performing code clean-up before the object is reclaimed by the garbage collector.

它是一个存在于类中的方法,在垃圾收集器回收其任何对象之前调用该方法。finalize()方法用于在垃圾收集器回收对象之前执行代码清理。

回答by Jared Rummler

final

最终的

It is used in the following three cases:

它用于以下三种情况:

  1. If the final keyword is attached to a variable then the variable becomes constant i.e. its value cannot be changed in the program.
  2. If a method is marked as final then the method cannot be overridden by any other method.
  3. If a class is marked as final then this class cannot be inherited by any other class.
  1. 如果 final 关键字被附加到一个变量上,那么这个变量就变成了常量,即它的值不能在程序中改变。
  2. 如果一个方法被标记为 final,则该方法不能被任何其他方法覆盖。
  3. 如果一个类被标记为 final,那么这个类不能被任何其他类继承。

source: http://www.go4expert.com/articles/final-finally-finalize-java-t28061/

来源:http: //www.go4expert.com/articles/final-finally-finalize-java-t28061/

finally

最后

The finallyblock always executes when the try block exits. This ensures that the finallyblock is executed even if an unexpected exception occurs. But finallyis useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

finally块总是在 try 块退出时执行。这确保finally即使发生意外异常,块也能执行。但是,finally是的不仅仅是异常处理更加有用-它允许程序员避免不慎被绕过具有清除代码returncontinuebreak。将清理代码放在 finally 块中始终是一个好习惯,即使没有预料到异常也是如此。

source: http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

来源:http: //docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

finalize

敲定

The finalizemethod is called when an object is about to get garbage collected. That can be at any time after it has become eligible for garbage collection.

finalize当对象即将被垃圾收集时调用该方法。这可以是在它符合垃圾收集条件之后的任何时间。

Note that it's entirely possible that an object never gets garbage collected (and thus finalizeis never called). This can happen when the object never becomes eligible for gc (because it's reachable through the entire lifetime of the JVM) or when no garbage collection actually runs between the time the object become eligible and the time the JVM stops running (this often occurs with simple test programs).

请注意,一个对象完全有可能永远不会被垃圾收集(因此finalize永远不会被调用)。当对象永远不符合 gc 的条件时(因为它在 JVM 的整个生命周期中都可以访问),或者在对象符合条件的时间和 JVM 停止运行的时间之间没有实际运行垃圾回收(这通常发生在简单的测试程序)。

There are ways to tell the JVM to run finalizeon objects that it wasn't called on yet, but using them isn't a good idea either (the guarantees of that method aren't very strong either).

有多种方法可以告诉 JVMfinalize在尚未调用的对象上运行,但使用它们也不是一个好主意(该方法的保证也不是很强)。

If you rely on finalizefor the correct operation of your application, then you're doing something wrong. finalizeshould onlybe used for cleanup of (usually non-Java) resources. And that's exactlybecause the JVM doesn't guarantee that finalizeis ever called on any object.

如果您依赖finalize应用程序的正确操作,那么您就做错了。finalize应该用于清理(通常是非 Java)资源。这正是因为 JVM 不保证会finalize在任何对象上调用。

source: https://stackoverflow.com/a/2506509/1048340

来源:https: //stackoverflow.com/a/2506509/1048340



This is all results of a quick Google search; which you should have done before posting the question :P

这是快速谷歌搜索的所有结果;在发布问题之前你应该做的:P

回答by FrederikDS

The final keyword depends on where you use it:

final 关键字取决于您在哪里使用它:

  • public final class ..., here you say that this class cannot be a super class (so no one can inherit this).
  • public final String someField, here you say that the String someFieldcannot be changed (after it has been initialized for the first time of course).
  • public final myMethod() { ... }, here the method cannot be overriden in a subclass.
  • public final class ...,这里你说这个类不能是超类(所以没有人可以继承这个)。
  • public final String someField,这里你说 StringsomeField不能改变(当然是在第一次初始化之后)。
  • public final myMethod() { ... },这里的方法不能在子类中被覆盖。

A finally block is used to get some code to run irrelevant whether the try catched the exception:

finally 块用于获取一些与 try 是否捕获异常无关的代码运行:

try {
    Random rand = new Random();
    if (rand.nextInt(2) == 0) { throw new Exception(); }
    System.out.println("You'll get here 50% of the time (when no exception is thrown)");
catch (Exception ex) {
    System.out.println("This should happen 50% of the time.");
} finally {
    System.out.println("You will ALWAYS get here!");
}

The finally method is something like this: protected void finalize(), this can be overriden by parent (@Override), like this:

finally 方法是这样的:protected void finalize(),这可以被父 ( @Override)覆盖,如下所示:

@Override
protected void finalize() {
    System.out.println("Do something");
}

The finalize-method should be run when garbage collection decides to remove the object. However this only happens when there are no references to the object. However it has some serious downsides. I would only use it when I would have some native data stored somewhere that has to be freed. But you'll probably almost never do that.

当垃圾回收决定删除对象时,应运行 finalize-method。然而,这只发生在没有对对象的引用时。然而,它有一些严重的缺点。我只会在我将一些本地数据存储在某个必须被释放的地方时使用它。但你可能几乎永远不会这样做。

Hope this helps.

希望这可以帮助。