Wednesday, December 4, 2013

When to make a method final in Java

Final keyword in Java is not as mysterious as volatile or transient, but still it creates lot of doubts on programmers mind. I often receives questions like, When to make a method final in Java or When to make a method static in Java, later I answered in my earlier post. Questions like this is not trivial, knowing what a keyword does is just small part of mastering that functionality. Similar to real world, where knowing that a sword can cut lot of things is not enough for a warrior to survive, you need to know how to use that and more importantly, use if effectively. Final keyword can be applied to class, methods and variable and has different meaning for each of them, but the motive remains same, it state completeness, it opposes change. For example, final class can not be extended, value of final variable can not be change and a final method can not be overridden in Java. This gives you first hint, when to make a method final in Java, obviously to prevent subclass for changing it's definition, technical preventing it from overridden. There are lot of clues on How to use final keyword on methods in Java API itself, one of the prime example of this java.lang.Object class, which declares a lot of method final including wait method with timeout. Another example of making a method final is template method, which outlines algorithm in Template method design pattern. Since, you don't want a sub class to change the outline of algorithm, making it final will prevent any accidental or malicious overriding. In this tutorial, we will learn few things, which will help you to effectively use final keywords with Java methods.
Read more �

No comments:

Post a Comment