可以在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热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短