在Java中声明方法/构造函数final时会发生什么?
只要将方法定型为最终方法,就不能覆盖 它。也就是说,您不能从子类提供对超类的final方法的实现。
即,使方法成为最终方法的目的是防止从外部(子类)修改方法。
但是,如果您尝试覆盖最终方法,则会生成编译时错误。
示例
interface Person{
void dsplay();
}
class Employee implements Person{
public final void dsplay() {
System.out.println("这是Employee类的显示方法");
}
}
class Lecturer extends Employee{
public void dsplay() {
System.out.println("这是讲师类的显示方法");
}
}
public class FinalExample {
public static void main(String args[]) {
Lecturer obj = new Lecturer();
obj.dsplay();
}
}输出结果
Employee.java:10: error: dsplay() in Lecturer cannot override dsplay() in Employee
public void dsplay() {
^
overridden method is final
1 error将构造函数声明为final
在继承中,只要您扩展类。子类继承除构造函数之外的所有超类成员。
换句话说,构造函数不能在Java中继承,因此您不能覆盖构造函数。
因此,在构造函数之前编写final毫无意义。因此,java不允许在构造函数之前使用final关键字。
如果尝试这样做,则使构造函数为final会生成编译时错误,提示“此处不允许使用修饰符final”。
示例
在下面的Java程序中,Student类具有一个最终的构造函数。
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("学生姓名: "+this.name );
System.out.println("学生年龄: "+this.age );
}
public static void main(String args[]) {
new Student().display();
}
}编译时错误
编译时,上面的程序生成以下错误。
Student.java:6: error: modifier final not allowed here
public final Student(){
^
1 error