Java 中可以重写构造函数吗?

java 8object oriented programmingprogramming

如果超类和子类具有相同的方法(包括名称、返回类型和参数),并且您尝试使用子类的对象调用它

则将调用子类中的方法。

构造函数看起来像方法,但实际上不是。它没有返回类型,其名称与类名相同。

但是,构造函数不能被重写。如果您尝试在子类中编写超类的构造函数,编译器会将其视为方法并期望返回类型,从而生成编译时错误。

示例


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

相关文章