In Java, what purpose do the keywords final
, finally
and finalize
fulfil?
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.
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".
The finally keyword is used to execute code (used with exceptions - try.. catch statements) no matter if there is an exception or not.
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.
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
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
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With