Why is constructor of super class invoked when we declare the object of sub class? (Java)

后端 未结 18 1402
误落风尘
误落风尘 2020-11-27 19:30

Consider this code:

class Test {
    Test() {
        System.out.println(\"In constructor of Superclass\");
    }

    int adds(int n1, int n2) {
        ret         


        
18条回答
  •  时光说笑
    2020-11-27 20:09

    "If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem."
    (source: https://docs.oracle.com/javase/tutorial/java/IandI/super.html)

提交回复
热议问题