在 Java 中声明 final 方法/构造函数会发生什么?
每当您把一个方法变为 final 的时候,您就不能重写它。也就是说您不能在子类中对超类中声明为 final 的方法的实现进行重写。
也就是说,把一个方法声明为 final 的目的是防止它被外部(子类)修改。
即使这样,如果您仍然尝试重写一个 final 方法,编译器将会产生编译时错误。
示例
interface Person{
void dsplay();
}
class Employee implements Person{
public final void dsplay() {
System.out.println("This is display method of the Employee class");
}
}
class Lecturer extends Employee{
public void dsplay() {
System.out.println("This is display method of the Lecturer class");
}
}
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP