Final keyword in Java and its various uses


Final keyword is used in three different way learn what are these. Use of final in Java language. Are final and finalize same?

The Final keyword is used in two ways in Java, either to prevent inheritance or to make a field constant or unchangeable. The final keyword has three different meaning for three different type of elements in Java. As described below:

Variable: the final keyword when applied to a variable makes its value constant. You can only assign its value once. But when you try to change it it will not change. As shown in the program below.

Method: when final keyword is applied to a method this will prevent that method from being overridden in any of the subclasses of current class. Again refer to the program for demonstration.


public class Final {
    final int a = 100;
    final int sum(int a, int b){
        return a+b;
    }
}

class SubFinal extends Final{
    SubFinal(){
        System.out.println("value of a is :"+a);
        System.out.println("the sum is:"+sum(5,5));
        //a = 200;
    }
    
    /*int sum(int a, int b){
        return 0;
    }*/
    
    public static void main(String[] args){
        new SubFinal();
    }
}

the output of this program is

value of a is :100
the sum is:10

I have made a class by the name of Final and there is a variable and method which has been made final. Now I extend this Final class into another class which is SubFinal. In the constructor of the SubFinal I have accessed both, the variable and the method which was made final. And you may see the output of this.

However you may notice the comments in the code, I commented this because this, if un commented will not allow me to compile the code. As in first case I am trying to reassign the value of a final variable and in second comment I am trying to override the final method which is against the rule of final keyword.

Now that we know the final in terms of variables and method let us see what effect it makes on the class.


final class SomeName{
	//class definition
}

class SubClass extends SomeName{
	//class definition
}

Now if you will try to compile this program this will not compile because you are trying to inherit a final class which is not allowed. Now I hope you have worked out these examples and understand the working of final.

Note: final is not applicable to constructors and you must not confuse final with finalize as these two has completely different meaning.