Sunday 10 April 2016

Why would you ever mark a class final?

You should mark a class final 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 find number of classes in the Java core libraries marked as final. For example, the String class cannot be sub-classed.

Thus 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.

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.