English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Once a method is designated as final, it cannotOverride It means that you cannot provide an implementation for the superclass's final method from the subclass.
That is, making a method final is to prevent modification of the method from the outside (subclass).
However, if you try to override a final method, a compilation error will occur.
interface Person{ void dsplay(); } class Employee implements Person{ public final void dsplay() { System.out.println("This is the display method of the Employee class"); } } class Lecturer extends Employee{ public void dsplay() { System.out.println("This is the display method of the Lecturer class"); } } public class FinalExample {}} public static void main(String args[]) { Lecturer obj = new Lecturer(); obj.dsplay(); } }
Output Result
Employee.java:10: error: dsplay() in Lecturer cannot override dsplay() in Employee public void dsplay() { ^ overridden method is final 1 error
In inheritance, as long as you extend the class. The subclass inherits all members of the superclass except for the constructor.
In other words, the constructor cannot be inherited in Java, so you cannotOverrideConstructor
Therefore, writing final before the constructor is meaningless. Therefore, Java does not allow the final keyword to be used before the constructor.
If you try to do this, making the constructor final will generate a compilation error, indicating that "modifier final is not allowed here".
In the following Java program, the Student class has a final constructor.
public class Student { public final String name; public final int age; public final Student() this.name = "Raju"; this.age = 20; } public void display() { System.out.println("Student name: "+this.name ); System.out.println("Student age: "+this.age ); } public static void main(String args[]) { new Student().display(); } }
The following error is generated when the program above is compiled.
Student.java:6: error: modifier final not allowed here public final Student() ^ 1 error