Thursday, 8 March 2012

final keyword in Java

•In Java, “final” keyword is used for three reasons:
1) To declare constant variables or named constants.
2) To declare final methods.
3) To declare final classes.

We have already seen how final is used to declare constant variables or named constants. Let’s see about rest of the two uses of “final”…

final methods:

•In inheritance if you don’t want a method in superclass to be overriden by a method in subclass, you will be declaring the method in the superclass as “final”. The syntax is as follows:
final return-type method-name(parameters)
{
      statement(s);
}
•An abstract method cannot be declared as “final” because, an abstract method must be overriden in the subclass.


•final methods can improve the performance(speed of execution) of the program.
•As final methods cannot be overriden, the compiler knows which method to invoke at the compile time itself.
•If the final method is very small, the compiler will replace the method calls with body of the method itself in the bytecode it will be generating after compilation.
•This type of methods are called “inline” methods. This is possible only in the case of final methods.

final class: 

•If you don’t want your class to be extended/inherited by another class, then you will declare the class as “final”.
Syntax for declaring final class is as follows:
final class ClassName
{
    member(s);
}
•A final class cannot be inherited by any other class.
•An abstract class cannot be declared as final.

No comments:

Post a Comment