Monday, February 4, 2013

what is final keyword in java?

When you use the keyword ‘final’ with a variable declaration, the value stored inside that variable cannot be changed come what may!!

So suppose you do this :

final int i =10;

After this, nowhere in your code can you change the value of ‘i’ i.e. ‘i’ will always have a value ’10' .

So i = 11; //will give you a compile time error.

Now, suppose you did not initialize the final integer ‘i’ while declaring it.

final int i;

Can you assign any value to this variable now?

Yes, you definitely can. But only once!

So,

final int i;

i = 10; //This is fine

i = 11; //Compiler error

Now that was the core stuff about ‘final’ . Let’s learn a bit more in detail about it.

The ‘final’ keyword can be used for a class declaration or method declaration.

What happens when you use ‘final’ for a class declaration?

A: You cannot have a sub class of a class declared final i.e. No other class can extend this class.

What happens when you declare a method as final?

A: Simply put, the method cannot be overridden.

Can you override a method(Not declared as ‘final’) present inside a final class?

A: Obviously Not. Since there’s no way to extend a class declared final there’s no way of overriding its methods!

What happens when I declare a method inside a class as both ‘private’ and ‘final’ ?

A: Making a class both ‘private’ and ‘final’ makes the ‘final’ keyword redundant as a private method cannot be accessed in its sub class. But hey, you’ll be able to declare a method of the same name as in the base class if the method has been made private in the base class. But then that doesn’t mean you’re overriding the method. You’re simply declaring a new method in the sub class.

Note: You cannot make an ‘abstract’ class or method as ‘final’ because an ‘abstract’ class needs to be extended which will not be possible if you mark it as ‘final’!

1 comment: