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

你离开我真会死。 提交于 2019-12-20 15:37:14

问题


Often these keywords confuse me.

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


回答1:


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.

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

Method When 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)

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


Finally block

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}


Finalize method

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




回答2:


Final:- It is used in the following cases:

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

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.

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.




回答3:


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.

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

finally

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is 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.

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

finalize

The finalize method 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.

Note that it's entirely possible that an object never gets garbage collected (and thus finalize is 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).

There are ways to tell the JVM to run finalize on 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).

If you rely on finalize for the correct operation of your application, then you're doing something wrong. finalize should only be used for cleanup of (usually non-Java) resources. And that's exactly because the JVM doesn't guarantee that finalize is ever called on any object.

source: 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




回答4:


The final keyword depends on where you use it:

  • 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 someField cannot 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.

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

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:

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

Hope this helps.




回答5:


The java Final keyword can be used in many context.

  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

The finally Block

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. read more

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

Main issue with finalize method 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



来源:https://stackoverflow.com/questions/27815947/difference-between-final-keyword-finally-block-and-finalized-method-in-java-thr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!