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

后端 未结 18 1417
误落风尘
误落风尘 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 19:57

    I'll try to answer this from a different perspective.

    Suppose Java didn't call the super constructor for you automatically. If you inherit the class, you'd have to either call the super constructor implicitly, or rewrite it yourself. This would require you to have internal knowledge of how the super class works, which is bad. It would also require to to rewrite code, which is also not good.

    I agree that calling the super constructor behind the scenes is a little unintuitive. On the other hand, I'm not sure how they could have done this in a more intuitive way.

提交回复
热议问题