Decoding “final” in Java

Girijesh Chandravanshi
2 min readNov 12, 2017

--

In Java we have the “final” keyword, let's understand its meaning. final can be used in three ways, with

  1. class
  2. method
  3. variable

Let’s see all these uses:

  1. final with class.

When used with class, it ensures that the class declared as final cannot be inherited.

final class A{
}
public class B extends A{
public static void main(String args[]){ System.out.println("Hello World");
}
}

Here in the above code, I am trying to extend class A, which is declared as final. But Java specification will not allow me to do that, since class A is final. On compiling the above code you will get the following error:

B.java:3: error: cannot inherit from final A
class B extends A{}
^
1 error

in java, our very own String class is an example of a final class.

2. final with methods

when used with methods the final keyword ensures that one can’t override that particular method.

class A{
public final void print(){
System.out.println("From A");
}
}
class B extends A{
public final void print(){
System.out.println("From B");
}
}
public class TestFinal{public static void main(String args[]){
B b = new B();
b.print();
}
}

In the above code, I am trying to override the final print method of class A, by declaring exactly the same method is class B. But Java would not allow me that.

On compilation it will give an error saying that class B cannot override the print method which is declared as final in A class, Here the error I got when I tried to compile it:

TestFinal.java:7: error: print() in B cannot override print() in A
public final void print(){
^
overridden method is final
1 error

Although we can overload it (will cover that in some other article).

3.final variable

when we declare a variable final, it becomes constant, which means you can initialize it once, and then after its value can’t be changed.

class A{ 
/* final variable should be declared in UPPERCASE only in that way it would be easy to distinguish between final and non-final variable. */
private final int FINAL_INT;
public A(){
FINAL_INT = 20;
}

public void print(){
FINAL_INT = 30;
System.out.println(FINAL_INT);
}
}
public class TestFinal{
public static void main(String args[]){
A a = new A();
a.print();
}
}

Here if you see I am trying to reassign the final variable with 30 in the print method. When I tried to compile it will give me a compilation error. Java doesn’t allow you to change the final variable. It will give the following error:

TestFinal.java:8: error: cannot assign a value to final variable FINAL_INT
FINAL_INT = 30;
^
1 error

--

--