Java final
Keyword
final
is a Keyword in Java, and it can be used to decorate,
- class
- variable
- method
final
on Class
final
can be used to decorate a class, and we called a class with final
defind as final class.
If a class is defined as final
, then, this class can't be inherited by any sub class.
Usually, an immutable class always declared as final, such as String class.
final
on Variable
final
also can be used to decorate a variable.
public final class Test {
private final String name = "aa";
private final int age;
public Test(int age) {
this.age = age;
}
public static void main(String[] args) {
final var app = new Test(12);
...
}
}
-
final
can be used to define class variable, once thatfinal
variable is assigned, it's value can't be changed.The final variable can be assigned in its declaration, or in a later static code block, constructor or any method, but it only can be assigned once.
-
final
also can be used to define a local variable, once thatfinal
variable is assigned, it's value can't be changed.
For example,
public final class Test {
private final String name = "aa";
private final int age;
public Test(int age) {
this.age = age;
this.name = "new name"; // compile error
}
public static void main(String[] args) {
final var app = new Test(12);
app = new Test(13); // compile error
}
}
final
on Method
final
also can be used on a method. When a method is defined as final
, that method can't be overridden in sub class.
For example,