Some important facts about final keyword of Java Language
final is a keyword in java which is used as a modifier for a classes, methods, instance variables and local variables.
This is one of the non-access modifier.
When a class is marked as 'final', it can never be extended. i.e the final classes cannot be sub classed. We rarely mark a class as final because this stops us from using java inheritance - which is one of the key pillars of Java Technology. A class is marked as final so that no one can override the methods of that class - As a security measure. Imagine the consequences of badly overriding methods of java.lang.String class (which is a final class).
A class can never be marked as both 'final' and 'abstract', both of which are contradictory to each other.
When a method is marked as final, it can never be overridden, even though the class itself is non-final.
When an instance variable is marked as final, once it is given a value, it can never change. If we assign a reference variable to an object, then we can never reassign a new object to that reference variable. Although we can change the properties of that object. All final variable must be initialized by a value explicitly before each constructors finishes running. Else the compiler will throw an exception.
final is the only modifier that can be applied for a method local variable. It should be given a value during variable declaration.
No comments:
Post a Comment