Skip to content
thesarfo

Concept

The final Keyword

The three uses of Java's final keyword — final variables, methods, and classes.

views 0

There are three uses of the final keyword:

  1. Final variable
  2. Final method
  3. Final class

Final variable

A constant — its value is fixed and cannot be modified.

class My {
final int MIN = 1; // can be initialized and defined at once
final int NORMAL;
final int MAX;
static {
NORMAL = 5; // can be initialized inside a static block
}
My() {
MAX = 10; // can be initialized inside a constructor
}
}

Final method

These methods cannot be overridden.

class Super {
final void meth1() {
System.out.println("Hello");
}
}
class Sub extends Super {
// void meth1() {} // wrong — final methods cannot be overridden
void meth2() {
System.out.println("Bye");
}
}

Final class

These classes don’t support inheritance — they cannot be extended, but you can still create objects of them.

final class Super {
// some code here
}
// class Sub extends Super { } // wrong — final classes cannot be extended