Saturday, June 20, 2009

Why Java Classes are not marked "final"

final keyword is a main feature of Java language.It is mostly used to define the constant values.Since it is a non-access modifier ,then question arises can final keyword be used with the Java classes.The answer simply is no,we can never ever use a final modifier before a Java class but Important thing here is to remember(REALLY IMPORTANT) that if you wish, methods of your class must not be overridden then only use final keyword before class declaration.Declaring a Java class as final means you can never subclass or extend the final class.That is it is strictly against the inheritance property.So does it violate the Object Oriented property of Java?So why we should use it?You should make a final class only if you need an absolute guarantee that none of your methods in that class will ever be overridden.

If you want security of your code and don't want any body to change it ,mark your class as final thus your implementation will remain secret and can never be changed.

The main example here is that the main Java core libraries are also marked as final.Assume a situation where we cannot guarantee that how String class going to work on any system your application is running on.

Use final modifier only when you think that you need no improvements in future because once declared as final a class cannot be subclassed and improved.

Example:-

public final class test{
public void myMethod(){ //your code }
}

class testingtest extends test{ //your code }

Compiling above code snippet would give output like following:-
Can't subclass final classes:class test class testingtest extends test
1 error

As told earlier use final in the extreme conditions where you require quite a lot of safety and security.If your class needs an improvement and you don't have source code, you now better what you have to do!!!!!

Home
Local Variable , Instance Variable and Shadowing
India Online all Indian Stuff

0 comments:

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP