1.

Usage of Final keyword in Java

Answer»

The final KEYWORD is a type of modifier in Java. It is of the non-access type. It can only be applied to a variable, method or a class.

Class that are final cannot be extended. Methods that are final cannot be used for method overriding in child class.

The final variables have constant value which are not changeable throughout the program. This MEANS they need to be initialized along with their declaration, OTHERWISE they would be blank final variables, which can be later initialized only once. If a final variable is used as a reference to an object, it cannot be used as a reference to another object.


1. If we try to change the value of the final variable, it will generate an error:

public class Example   {      STATIC final int x=10;             public static void main(String args[])      {           x = 5; // re-assignment of final variable          System.out.println(x);     }  }

This program will generate a compile time error

$javac Example.java Example.java:9: error: cannot assign a value to final variable x          x= 5;           ^ 1 error

2. If we try to inherit a final class in a subclass, the compiler will show an error.

final class Superclass { static int x=5; } public class Example extends Superclass {      public static void main(String []args)    {     System.out.println(x);    } }

The error message is as follows:

$javac Example.java Example.java:5: error: cannot inherit from final Superclass public class Example extends Superclass                              ^ 1 error

3. If we try to override a final class, it will generate an error:

class Superclass {  int x=5;  final void add() {     int j=x+5;     System.out.println(j); } } public class Example extends Superclass {      void add()    {        int a=5,b=10;        System.out.println(a+b);    }    public static void main(String []args)    {     Example e=new Example();     e.add();    } }

The error generated is as follows

$javac Example.java Example.java:12: error: add() in Example cannot override add() in Superclass    void add()         ^  overridden method is final 1 error


Discussion

No Comment Found