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
Android
Python
C 语言
C++
C#
MongoDB
MySQL
JavaScript
PHP