Final keyword in Java2 min read

What is final keyword in Java?

A final keyword in Java can be declared as a member, class, method, and function parameter. Anything declared as final prevents its contents from being a modifier.

The final keyword in java is a non-access modifier that prevents classes, attributes, and methods from being changed (impossible to inherit or override). It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.

Final variable

  • A final variable is a constant. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.
  • This applies to instance, static and local variables including the final parameter. A final variable must be initialized at the time of declaration or before its use. Variables defined in an interface are implicitly final.

Example: final double pi = 3.1428571;

Final Class

  • A class declared as final cannot be extended.
  • The keyword final with a class declares a lower boundary of its implementation inheritance hierarchy.
  • The final keyword should be used with the class whose definition is complete i.e. that class has implementations of all the methods.
  • A final class cannot be of type abstract because the final class must be complete but an abstract class is incomplete.
  • Example of Java’s inbuilt final class in java.lang.String.

Example:

final class Cat extends Animal{
  // instance variable declaration
}

Final method

A final method cannot be overridden because the final keyword prevents method overriding.

Example:

class One {
  final void method(){
    System.out.println ("Final Method");
  }
}

class Two extends One {
  void method(){ 
    //error
    System.out.println("Invalid");
  }
}

Final parameter

  • In a function definition, parameter can be declared with the final keyword.
  • A final parameter is also known as a blank final variable.
  • A final variable is blank until a value is assigned to it at the time of method invocation.
  • Once a value is assigned to the final parameter, it can not be changed during the lifetime of the variable.
  • The compiler can treat such blank final variables as constants for code optimization purposes.

Example:

public void paint(int code, final double price){
  price = purchase * 1.50;
  // other code
}

Share:

Leave a Reply