The java final modifier can be attached to all classes, methods and variables, Each has a different meaning.
If you add the final modifier to a class, that class cannot be inherited. An error will occur at the compilation stage.
//final modifier class
final class FinalDemo {
String name = "Class with final";
public final void getInfo() {
System.out.println(this.name);
}
}
//Small class
class FinalDemoChild extends FinalDemo {
}
class MyApp {
public static void main(String[] args) {
FinalDemoChild demo = new FinalDemoChild();
}
}
Execution result
$ java Myapp
Error:(8, 21) java: final final_Cannot be inherited from demo
If you add final to a method of a class, you cannot override it in the method child class.
//Class with final
class FinalDemo {
String name = "Class with final";
public final void getInfo() {
System.out.println(this.name);
}
}
//Small class
class FinalDemoChild extends FinalDemo {
@Override
public void getInfo() {
System.out.println(this.name + "Small class");
}
}
class MyApp {
public static void main(String[] args) {
FinalDemoChild demo = new FinalDemoChild();
}
}
Execution result
$ java MyApp
Error:(11, 17) java:FinalDemoChild getInfo()Is the Final Demo getInfo()Cannot be overridden
Overridden method is final
If you add final to a variable (field), you cannot reassign it. That is a constant. Since it is not necessary to change it with instance, it seems that it is often declared with a class variable with static. Also, as in other languages, constants are written in all capital letters.
//Class with final
class FinalDemo {
public static final String NAME = "Variable with final";
}
class MyApp {
public static void main(String[] args) {
//Change constant
FinalDemo.NAME = "Reassignment";
}
}
Execution result
$ java MyApp
Error:(9, 18) java:You cannot assign a value to the final variable NAME
Recommended Posts