Summary: In this tutorial, you will learn about final keyword in Java. You will learn the significance of final when used with different entities such as variable, function and class with the help of examples.

final in Java

In Java, the final keyword can be used in several contexts to indicate that something cannot be modified.

  1. When applied to a variable, it means that the value of the variable cannot be changed once it has been assigned.
  2. When applied to a method, it means that the method cannot be overridden in a subclass.
  3. When applied to a class, it means that the class cannot be subclassed.

Note that variables and methods that are declared final must be initialized when they are declared, as they cannot be modified later.

Here are complete examples demonstrating the use of the final keyword in each of the three contexts mentioned above:

1. Final Variable

public class Example {
    final int x = 10; // x is a final variable and must be initialized when declared

    public void doSomething() {
        x = 20; // This would cause a compile-time error because x is a final variable
    }
}

Here, a class named Example is defined with a final instance variable x. The value of x is initialized to 10 when it is declared.

The doSomething method attempts to change the value of x to 20, but this causes a compile-time error because x is a final variable and its value cannot be changed after it has been initialized.

2. Final method

public class Example {
    public final void doSomething() {
        // Method implementation
    }
}

public class SubExample extends Example {
    @Override
    public void doSomething() { // This would cause a compile-time error because doSomething() is a final method in the superclass
        // Method implementation
    }
}

In this example, a class named Example is defined with a final method named doSomething. The doSomething method has an implementation, but the details of the implementation are not shown in the example.

A subclass of Example named SubExample is then defined, and it attempts to override the doSomething method from the superclass.

However, this causes a compile-time error because the doSomething method is marked as final in the superclass, which means it cannot be overridden in a subclass.

3. Final class

public final class MyClass {
    // Class definition
}

public class SubClass extends MyClass { // This would cause a compile-time error because MyClass is a final class and cannot be subclassed
    // Class definition
}

Here example, a final class named MyClass is defined. The class has a definition, but the details of the definition are not shown in the example.

A class named SubClass is then defined, and it attempts to extend MyClass. However, this causes a compile-time error because MyClass is a final class and cannot be subclassed.

This means that no other class can inherit from MyClass and must instead use it directly.


Leave a Reply