If you want to restrict the user from inheriting the class, prevent overriding of a method and declaring constant then use final keyword. final keyword is applied to class, variables, and method.
Static variable that is declared final is called final static variable. It can be initialized at the point of declaration or inside static initializer block. You cannot initialize it in the constructor.
class StaticExample { final static int counter1=1; final static int counter2; static { counter2=10; } }
Instance variable that is declared final is called final instance variable. You can initialize it in the constructor or instance initializer block. You are not allowed to initialize it in instance methods.
class InstanceExample { final int counter1=1; final int counter2; public InstanceExample() { counter2=10; } }
Local variable that is declared final is called final local variable. You can only initialize it inside a method.
class LocalExample { public void display() { final int counter1=10; } }
When you call a method, parameters of that method if present are initialized. If you have declared them as final, then you cannot reassign a value to it.
class MethodParameterExample { public int add(final int a, final int b) { a=12; //Compiler error } }
To prevent overriding of a method in a drived class, a base class can declare its method as final.
class A { public final void display() { System.out.println("I am in A class"); } } class B extends A { public void display() { System.out.println("I am in B class"); } public static void main(String args[]) { B b = new B(); b.display(); } }
The above code will give compile time error.
If a class is declared final, then that class cannot be extended.
final class A { public void display() { System.out.println("I am in A class"); } } class B extends A { public void display() { System.out.println("I am in B class"); } public static void main(String args[]) { B b = new B(); b.display(); } }
The above code will give compile time error.