Set a variable to final
, to prevent it from being overridden/modified:
public class Main {
final int x = 10;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}
The final
keyword is a non-access modifier used for classes, attributes and methods, which makes them non-changeable (impossible to inherit or override).
The final
keyword is useful when you want a variable to always store the same value, like PI (3.14159...).
The final
keyword is called a "modifier". You will learn more about these in the Java Modifiers Chapter.
Read more about attributes our Java Class Attributes Tutorial.
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!