在 Java 中,如果将方法/构造函数声明为 final,会发生什么情况?
java 8object oriented programmingprogramming更新于 2025/9/24 3:24:17
如果将方法声明为 final,则无法覆盖它。也就是说,您无法在子类中提供超类 final 方法的实现。
也就是说,将方法声明为 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("这是 Lecturer 类的显示方法");
}
}
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 类有一个 final 的构造函数。
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("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+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

