Calling of Constructors in a Java

2019-07-20 20:58发布

In the book Java: The complete reference

// Demonstrate when constructors are called.
// Create a super class.
class A {
     A() {
        System.out.println("Inside A's constructor.");
     }
}
// Create a subclass by extending class A.
class B extends A {
      B() {
             System.out.println("Inside B's constructor.");
      }
 }
// Create another subclass by extending B.
class C extends B {
    C() {
        System.out.println("Inside C's constructor.");
    }
}
class CallingCons {
    public static void main(String args[]) {
        C c = new C();
    }
}

Output: Inside A’s constructor Inside B’s constructor Inside C’s constructor

It is demonstrating how the constructor of a subclass is called. But why are constructors of the super class called in the absence of a super() constructor.

Why did the Java Language designers consider it necessary to do so?

7条回答
Viruses.
2楼-- · 2019-07-20 21:26

Imagine class C accessing an unitialized variable of class B or A. Implicitly calling constructors of class B-->class A makes sure that you are always accessing initialized variables of inherited classes(A or B)

查看更多
登录 后发表回答