May 9, 2022

final in Java With Examples

final keyword in Java can be used with a field, method or class. In whichever context you use final in Java, it restricts the access in some way.

  • Final variable– If a field is declared as final its value can’t be changed once assigned.
  • Final method– A method declared as final can’t be overridden.
  • Final class– A class declared as final can’t be extended.

Final variable in Java

When a field is declared as final it can’t be modified thus making it a constant. Since a final variable is constant it is considered good practice to give final variable name in all uppercase.

Since the value of a final variable can’t be modified so final variable can be initialized only once. That initialization can be done in following ways-

  • You can initialize a final variable when it is declared. As example- final int WEEK_OF_DAYS = 7;
  • you can defer the assignment to do it in a constructor, initializer block or static block (if field is static too along with final). A final variable that is not initialized when it is declared is called a blank final variable in Java.

Examples of final field in Java

When declared but not initialized– In that case you will get a compile time error that the blank final field may not have been initialized.

final blank variable
Initializing final field in a constructor
public class FinalDemo {
  final int DAYS_IN_WEEK;
  FinalDemo(){
    DAYS_IN_WEEK = 7;
  }

  public static void main(String[] args) {
    FinalDemo finalDemo = new FinalDemo();
  }
}
Initializing final field in an initializer block
public class 
public class FinalDemo {
  final int DAYS_IN_WEEK;
  {
    DAYS_IN_WEEK = 7;
  }

  public static void main(String[] args) {
    FinalDemo finalDemo = new FinalDemo();
  }
}
Initializing static final field in a static block
public class 
public class FinalDemo {
  final static int DAYS_IN_WEEK;
  static{
    DAYS_IN_WEEK = 7;
  }
  public static void main(String[] args) {
    FinalDemo finalDemo = new FinalDemo();
  }
}

Trying to change value of a final field – That will result in compiler error as final field can’t be modified once initialized.

final constant java

Final variable in a method

In the above examples final field was at the class level but you can have a final variable in the methods too. Declaring a local variable final has the same effect too; value can’t be assigned to it more than once.

Even method parameters can be declared final in Java so that the parameter values can’t be changed. For example- public void getValue(final int amount, final int years)

Final variable holding object reference

In case of final variable holding an object reference you can change the value of any object field but you can’t change the reference held by the final variable. That makes sense because in case of object reference the value of the variable is the memory reference so that can’t be changed in case it is final. Let’s see an example.

Final object reference Java example

Here we have an Employee class with age and name fields. A final variable employee holds reference to an Employee object. In the code you can see that field values can be changed but trying to change the reference employee = new Employee(); will cause compile time error.

class Employee{
  int age;
  String name;
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
}

public class FinalDemo {
  final int DAYS_IN_WEEK = 7;

  public static void main(String[] args) {
    // final variable holding object reference
    final Employee employee = new Employee();
    // setting field values
    employee.setAge(25);
    employee.setName("Jack");
    System.out.println("Employee Age " + employee.getAge());
    // changing field value - That is OK
    employee.setAge(35);
    System.out.println("Employee Age " + employee.getAge());
    // Can't change the reference 
    employee = new Employee(); // Compiler error
  }
}

Final Method in Java

You can also declare a method as final in Java making it a final method. A final method can’t be overridden.

If a method is declared as final in the parent class then child classes can’t override that method and change the implementation.

If you have any method in the class which you consider complete functionality wise, then you can declare it as final method so that the same implementation is used by the child classes.

Final method Java example
final method in Java

Here you can see that trying to override displayValue() method in the child class results in compiler error- Cannot override the final method from Parent

final method performance benefits

Declaring methods as final may also result in performance improvement in your code. In Java calls to methods are generally resolved at run time which is known as dynamic or late binding.

When you mark a method as final, Java compiler knows that the method can't be overridden, so call to that method can be resolved at compile time itself. This is known as static or early binding. If the method call is resolved at run time then the method can be inlined meaning the method code can be put at the place from where it is called. That avoids the overhead of method call at runtime resulting in performance improvement.

Final class in Java

If you declare a class as final in Java then that class can’t be extended (You can’t inherit from a final class). In Java declaring a class as final helps in the following ways-

  1. If you have a class where you are sure that it has all the required functionality and should not be subclassed to add any extra functionality then it should be declared as final in Java.
  2. Another particularly useful scenario where marking a class as final is needed is when creating an immutable class like the String class.
Final class example
final class in Java

Note that you can't declare a class as both final and abstract in Java. As abstract class by design relies on subclass to provide complete implementation so restricting it by marking a class as final too is a contradiction thus not permitted.

final and abstract

That's all for the topic final in Java With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment