Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil? [closed]

In Java, what purpose do the keywords final, finally and finalize fulfil?

like image 556
Pat R Ellery Avatar asked Oct 18 '11 22:10

Pat R Ellery


People also ask

What purpose do the keywords final finally and finalize fulfill?

The final keyword can be used with class method and variable. A final class cannot be inherited, a final method cannot be overridden and a final variable cannot be reassigned. The finally keyword is used to create a block of code that follows a try block.

What is the purpose of the keyword final in Java?

The final keyword is a non-access modifier used for classes, attributes and methods, which makes them non-changeable (impossible to inherit or override). The final keyword is useful when you want a variable to always store the same value, like PI (3.14159...). The final keyword is called a "modifier".

What is the purpose of keyword finally?

The finally keyword is used to execute code (used with exceptions - try.. catch statements) no matter if there is an exception or not.

What is final vs finally vs finalize in Java?

Final is a "Keyword" and "access modifier" in Java. Finally is a "block" in Java. Finalize is a "method" in Java. Final is a keyword applicable to classes, variables and methods.


1 Answers

final

final can be used to mark a variable "unchangeable"

private final String name = "foo";  //the reference name can never change 

final can also make a method not "overrideable"

public final String toString() {  return "NULL"; } 

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

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 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(); } 
like image 82
krico Avatar answered Sep 26 '22 00:09

krico