构造函数可以在 Java 中重写吗?
如果父类和子类拥有相同的方法(包括名称、返回类型和参数),并且尝试使用子類的函数调用它
则调用子类中的方法。
构造函数看起来像方法,但它不是。它没有返回值类型,并且其名称与类名称相同。
但是,构造函数无法被重写。如果您尝试在子类编译器中编写一个超类构造函数,它会将其视为一个方法并期望一个返回类型,并生成一个编译时错误。
示例
class DemoTest{
DemoTest(){
System.out.println("This is the constructor of the demo class");
}
}
public class OverridingConstructor extends DemoTest {
DemoTest(){
System.out.println("This is the constructor of the demo class");
}
}
输出
C:\Sample>javac Example.java
Example.java:2: error: class Sample is public, should be declared in a file named Sample.java
public class Sample {
^
1 error
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP