What are final methods in Java

Selasa, 11 Februari 2014

Hello guys, Java Code Online welcomes you back again, and is going to discuss about the final methods in the Java Programming Language. The Java language provides its users with many resources and tools. There are many features in the Java language that makes it very powerful. Final access modifier is one of those features, that makes Java really solid.

If a method is marked as final, then it implies that it cannot be overridden. So any class that extends the class containing the final methods, cannot override the methods marked final. If any attempt is done to override a final method in a sub class, leads to Java Compiler error.

An example of a final method in a class is:-

/////////////////////////////

class TestFinal{

public final void finalTested(){
//Working of this method
}

//Some other methods

}

/////////////////////////////

The above Java code depicts the use of final when applied to methods.

You may be thinking that what is the advantage of making a method final, though it defies the basic principle of OOPS, that is the final methods are non supportive of inheritance, as they cannot be overridden. It implies that they cannot be extended, and so also makes Polymorphism not feasible for it.

Hmmm... it implies that there are many drawbacks of the final method, but still Java provides it. So there must be some advantage of it also... Lets check them out.

Think of a scenario, that you have made a class, and you want a particular method to be implemented in exactly a particular way, and one should be never allowed to change this implementation. There are many possibilities for it. Like there are many methods in the Java API, which are guaranteed to work in a fixed way, and there is no way we can change them. This scenario calls for marking the method of the class as final. Later I will tell you about the Template Design Pattern which is based on this concept.

I hope you got my point. Whenever you want the methods to be locked, and should not be allowed to be modified, then final is the keyword to be used. The class can still be inherited since it is not marked final, and so the concept of Inheritance and Polymorphism can easily work here, but only for methods which are not marked as final in the super class.

Hope that the article was helpful to you all in understanding the final methods in Java. Keep ticking Java Code Online for more details on Java.

Related Posts by Categories

0 komentar:

Posting Komentar

Copyright © 2010 Computer Tips and Trick | Powered By Blogger