English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn about Java final variables, final methods, and final classes through examples.
In Java, the final keyword is used to represent constants. It can be used with variables, methods, and classes.
Any entity (variable, method, or class) once declared final can only be assigned once. That is,
final variable cannot be reinitialized with another value
final method cannot be overridden
final class cannot be inherited
In Java, we cannot change the value of a final variable. For example,
class Main { public static void main(String[] args) { //Create a final variable final int AGE = 32; //Attempt to change a final variable AGE = 45; System.out.println("Age: " + AGE); } }
In the above program, we created a final variable named age and tried to change the value of the final variable.
Bei der Ausführung des Programms wird die folgende Fehlermeldung angezeigt, die einen Kompilierungsfehler anzeigt.
cannot assign a value to final variable AGE AGE = 45; ^
Note:It is recommended to use uppercase letters to declare final variables in Java.
Before understanding final methods and final classes, make sure you understandJava Vererbung.
In Java, this final method cannot be overridden by a subclass. For example,
class FinalDemo { //Erstellen Sie eine finale Methode public final void display() { System.out.println("This is the Final method."); } } class Main extends FinalDemo { //Versuchen Sie, eine finale Methode zu überschreiben public final void display() { System.out.println("Final method is overridden."); } public static void main(String[] args) { Main obj = new Main(); obj.display(); } }
In the above example, we created a final method named display() within the FinalDemo class. Here, the Main class inherits from the FinalDemo class.
We tried to override the final method in the Main class. When running the program, the following error message will appear, indicating a compilation error.
display() in Main cannot override display() in FinalDemo public final void display() { ^ overridden method is final
In Java, a final class cannot be inherited by another class. For example,
final class FinalClass {}} //Erstellen Sie eine finale Methode public void display() { System.out.println("Dies ist eine finale Methode."); } } class Main extends FinalClass { //Versuchen Sie, eine finale Methode zu überschreiben public void display() { System.out.println("Finalmethode überschreiben"); } public static void main(String[] args) { Main obj = new Main(); obj.display(); } }
Im obigen Beispiel haben wir eine finale Klasse namens FinalClass erstellt. Hier versuchen wir, die finale Klasse durch die Klasse Main zu vererben.
Bei der Ausführung des Programms wird die folgende Fehlermeldung angezeigt, die einen Kompilierungsfehler anzeigt.
cannot inherit from final FinalClass class Main extends FinalClass { ^