可以在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热门推荐
2 成都训练狗狗
3 怎么训练小狗狗
4 训练狗狗软件
5 如何训练狗狗拉屎
9 狗狗负重训练
10 狗狗多大可以训练大小便
11 怎么训练狗狗萨摩耶
12 狗狗训练书
13 鞍山狗狗训练
14 训练狗狗用品
15 怎样才能训练狗狗听话
16 狗狗如何训练大小便
17 怎样训练狗狗睡狗窝
18 训练狗狗工具