In Java, final keyword can be used with member variables, methods, local variables and classes.

In a nutshell the final keyword can be used with:

  • Variable
  • Method
  • Class

Final Variables

A variable which is declared by using final keyword is the final variables. we cannot make any changes to the value of the final variable. The final variables are just like the constants. The final variables which do not have any value are known as the blank final variables or uninitialized final variables. The final keyword can be initialized in constructor only. A static blank final variable can be initialized in static block only.

Let us have a look on the example:

<br />
public class Marks{</p>
<p>final int marks=50;//final variable</p>
<p>void run(){</p>
<p>marks = 90;</p>
<p>}</p>
<p>public static void main(String args[]){</p>
<p>Marks o1=new Marks();</p>
<p>o1.run();</p>
<p>}</p>
<p>}//end of class</p>
<p>

Final Method

The method which is made final cannot be overridden. Sub class can call the final method of the parent class but it cannot override the final method. The final methods are faster than the non final methods because they are not required to be resolved at runtime and they are joined at the compiled time.

Let us have a look on the example:

</p>
<p>public class fruits</p>
<p>{</p>
<p>final void run()</p>
<p>{    System.out.println(&quot;in fruit class&quot;);</p>
<p>}</p>
<p>}</p>
<p>&amp;nbsp;</p>
<p>class apple extends fruits</p>
<p>{</p>
<p>void run()</p>
<p>{    System.out.println(&quot;apple class&quot;);</p>
<p>}</p>
<p>&amp;nbsp;</p>
<p>public static void main(String args[])</p>
<p>{</p>
<p>apple a= new apple();</p>
<p>a.run();</p>
<p>}</p>
<p>}</p>
<p>

Final Class

The class declared using final keyword is known as final class. The final class is complete in nature and cannot be inherited.

Let us have a look at the example:

</p>
<p>public class fruits</p>
<p>class apple extends fruits</p>
<p>{</p>
<p>void run()</p>
<p>{    System.out.println(&quot;apple class&quot;);</p>
<p>}</p>
<p>public static void main(String args[])</p>
<p>{</p>
<p>apple a= new apple();</p>
<p>a.run();</p>
<p>}</p>
<p>}</p>
<p>

Some points to remember

  • Constructor cannot be declared as final.
  • The local final variable must be initialized during declaration.
  • The variables which are declared in an interface are by default final.
  • The final method cannot be overridden.
  • The final class cannot be inherited.