Monday, 27 March 2017

Why would you ever mark a class final, if you can't change value of final variable, inherit final class or override final method?


You should make a final class only if you need an absolute guarantee that none of the methods in that class will ever be overridden. 

If you're deeply dependent on the implementations of certain methods, then using final gives you the security that nobody can change the implementation out from under you.

You'll notice many classes in the Java core libraries are final. 


For example, the String class cannot be sub-classed. And thus immutability gives confidence to use String as Username, Password, Database Connection parameters, key in the HashMap. It is just because we can rely upon String that is not going to be tampered anyhow later.

Use final for safety, but only when you're certain that your final class has indeed said all that ever needs to be said in its methods. Marking a class final means, in essence, your class can't ever be improved upon, or even specialized, by another programmer just like String.


Suggestion 


So unless you have a serious safety or security issue, assume that some day another programmer will need to extend your class.


You may also like to read:

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.