我们可以在 java 中将构造函数声明为 final 吗?
java 8object oriented programmingprogramming
构造函数用于在创建对象时对其进行初始化。它在语法上类似于方法。不同之处在于构造函数与其类同名,并且没有返回类型。
无需显式调用构造函数,这些构造函数会在实例化时自动调用。
示例
public class Example { public Example(){ System.out.println("This is the constructor of the class example"); } public static void main(String args[]) { Example obj = new Example(); } }
输出
This is the constructor of the class example
final 方法
每当您将方法设为最终方法时,您都无法覆盖它。即您无法从子类中提供对超类最终方法的实现。
即,将方法设为最终方法的目的是防止从外部(子类)修改方法。
示例
在下面的 Java 程序中,我们试图覆盖最终方法。
class SuperClass{ final public void display() { System.out.println("This is a method of the superclass"); } } public class SubClass extends SuperClass{ final public void display() { System.out.println("This is a method of the superclass"); } }
编译时错误
编译时,上述程序会产生以下错误。
SubClass.java:10: error: display() in SubClass cannot override display() in SuperClass final public void display() { ^ 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