final Keyword in Java

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.

final Variable in Java

final static variable

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.

Example of final static variable

class StaticExample
{
	final static int counter1=1;
	final static int counter2;
	static
	{
		counter2=10;
	}
}

final instance variables

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.

Example of final instance variable

class InstanceExample
{
	final int counter1=1;
	final int counter2;
	public InstanceExample()
	{
		counter2=10;
	}
}

final local variable

Local variable that is declared final is called final local variable. You can only initialize it inside a method.

Example of final local variable

class LocalExample
{
	public void display()
	{
		final int counter1=10;		
	}
}

final method parameters

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.

Example of final method parameters

class MethodParameterExample
{
	public int add(final int a, final int b)
	{
		a=12; //Compiler error
	}
}

final Method in Java

To prevent overriding of a method in a drived class, a base class can declare its method as final.

Example of final method

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.

final Class in Java

If a class is declared final, then that class cannot be extended.

Example of final class

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.