Java

final keyword

Oct 8, 2013

final keyword

final is a keyword in java. If anyone have knowledge of c++ then you can compare final with const keyword.
Why to mark a variable or method of nature final?

Its a simple requirement which states that,something should never change and in no way anybody should change it. For example value of PI is 3.142 which has not changed since it is discovered,so if we want to block the user or anyone from changing such values we should use final keyword.Assume if you are developing an application where you are working on a specific area of land so the limitations of the land can be valid candidate for being final.

Example of a final variable:
final int MAX=100;

  " Only once in the lifetime a final variable can be on left hand side later has to be on right hand side. "  

final keyword working

Convention for final variables.

Any variable which is declared as final should be written totally in UPPER CASE.

Here are some inbuilt final variables.
Math.PI
JFrame.EXIT_ON_CLOSE
BorderLayout.WEST.


A method can also be defined as final

public final void m1()
{
}

Any method declared as final cannot be overridden.
So if the scenario arises for restricting the access of method in super class to a sub class can be done by defining a method as final.

Also a class can be defined as final.

final class MyClass
{
}

Once a class is defined as final class, it cannot act as a super class to any other class.
This is used when a class has to be defined as a last class in th hierarchy, an is required that no other class extends it.



 

Related Posts

Table Of Contents

;