如果超类和子类具有相同的方法(包括名称,返回类型和参数),并且尝试使用子类的对象对其进行调用
然后,调用子类中的方法。
构造函数看起来像方法,但不是。它没有返回类型,并且其名称与类名称相同。
但是,构造函数不能被覆盖。如果尝试在子类中编写超类的构造函数,则编译器会将其视为方法,并期望返回类型并生成编译时错误。
示例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
本文探讨了在面向对象编程中,超类与子类构造函数的关系及其与普通方法的区别。构造函数虽然类似方法但不具备返回类型,且无法被覆盖。通过具体示例展示了当尝试在子类中重写超类构造函数时,编译器如何处理此类情况。
902

被折叠的 条评论
为什么被折叠?



