Static, Final and Finally keywords
18 Jan 2014Final keyword means that a program cannot change the value of a final variable. But the actual meaning depends on its current context.
- Final class: cannot have subclass i.e. you can’t inherit it.
- Final variables: cannot be changed once initialized.
- Final methods: cannot be overridden i.e. you can have only one implementation of final method.
- Final vs String: String are immutable i.e. you cannot change value of a string once initialized. But
Final String abc
means that you cannot assign any other value to string variableabc
once initialized.
Static keyword represents that a particular method or variable is associated with a class rather than any particular instance of the class.
- Static variable/methods: is accessed by using the classname (or type) instead of classobject.
- Static Class: cannot be initialized i.e. you cannot create an object of a static class.
- Can you override a static method?: No. Reason: Geek explains: overriding a static method
- Can you overload a static method?: Yes.
- “An instance method cannot override a static method, and a static method cannot hide an instance method.”
- Both Static and Final keywords prevent a method from being overridden.
Finally: Every statement in the finally clause always execute, even if there is an exception in try block or we return from catch block, and thus it is used for doing clean up, closing port tasks. However, you cannot have return statement in it.
Additional notes (From Geeks for Geeks):
- Overriding (runtime polymorphism): A subclass provides a specific implementation of a method in superclass and the implementation to be executed is decided at run-time and decision is made according to the object used for call.
- Overloading (compile time polymorphism): It allows different methods to have same name, but different signatures, and the implementation to be executed is decided at compile time.
How to make an Immutable object?
- Make the class final.
- Make all members final.
- Make all methods private.
- Make sure that no methods modify the state of class.
- Initialize all members in a Static Initializer or in Constructor