Menu

Post image 1
Post image 2
1 / 2
0

final keyword in java?

DEV Community·SILAMBARASAN A·20 days ago
#EnA3kDEK
Reading 0:00
15s threshold

SILAMBARASAN A

In Java, the final keyword is used to stop changes.
It can be used with variables, methods, and classes.

  • If a variable is final, its value cannot be changed.
  • If a method is final, it cannot be overridden.
  • If a class is final, it cannot be inherited.

1. Final Variable

A final variable can only be assigned once.

final int x = 10;
x = 20; //  Error: cannot change value

Enter fullscreen mode Exit fullscreen mode

  • Acts like a constant
  • Must be initialized once (either at declaration or in constructor)

2. Final Method

A final method cannot be overridden by subclasses.

class Parent {
    final void show() {
        System.out.println("Final method");
    }
}

class Child extends Parent {
    void show() { //  Error
        System.out.println("Cannot override");
    }
}

Enter fullscreen mode Exit fullscreen mode


3. Final Class

A final class cannot be inherited (extended).

final class Animal {}

class Dog extends Animal { //  Error
}

Enter fullscreen mode Exit fullscreen mode

Example:

  • String class in Java is final
Read More