Keyword final

The final keyword is a special keyword in Java. It basically denotes a non-access modifier and it can be applied to Java fields, methods and classes.

Rules for final keyword:

1. Java fields declared as final become constant

2. Java methods declared as final cannot be overridden in subclass

3. Java classes declared as final can never be subclassed

 

Example

See the following example for demonstrating the final keyword.

TestFinal.java

class A {
final void m() { } //final method
}

class B extends A {
//the following statement violates rule 2
//void m() { } //m() in B cannot override m() in A: overridden method is final
}

final class S {} //final class

//the following statement violates rule 3
//class T extends S {} //cannot inherit from final S

public class TestFinal {

final static double PI = 3.14; //final field

public static void main(String[] args) {
//the following statement violates rule 1
//PI = 3.142; //cannot assign a value to a final variable
}
}

 

Explanation: In the above coding example, some of the code statements violate the rules for final keyword and are therefore marked with red color for identification. These statements are commented as well to avoid any compilation error. We have also passed comments to indicate that which rule is being violated here.

Now, we have the following observations—

1) The value of the final field PI can never be changed; doing so, will lead to compilation error.

2) The method m() defined in class A cannot be overridden in subclass B; hence, this statement will not be allowed by Java compiler.

3) The class named S cannot have subclasses; because the Java compiler does not allow a final class to be inherited.