Java 中可以将构造函数声明为 final 吗?
构造函数用于在创建对象时初始化对象。从语法上看,它类似于方法。区别在于构造函数与其类具有相同的名称,并且没有返回类型。
无需显式调用构造函数,它们在实例化时会自动调用。
示例
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 方法
每当你将一个方法设为 final 时,你就不能重写它。即你不能从子类为父类的 final 方法提供实现。
即,将方法设为 final 的目的是防止从外部(子类)修改方法。
示例
在下面的 Java 程序中,我们尝试重写一个 final 方法。
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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP