可以在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 爱生日祝福语简短独特