Java inheritance - constructors

前端 未结 5 705
盖世英雄少女心
盖世英雄少女心 2021-01-02 04:22

While studying for my finals, I came across the following statement in the book from which I am currently studying. Considering the following code :

class A         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-02 04:52

    It looks like the compiler tries to create a call to the superclasses default constructor with super(), which isn't avaliable:

    required: int
    found:    no arguments
    

    But back to your book: I've never heard of a rule that you can skip the super statement in a constructor if the actual constructor has the exact same parameter list as a constructor in the direct superclass. Only a call to the superclass's default constructor is added implicitly (super()) but that requires that the superclass has a default constructor.

    In contrast to what's written in your book (or in contrast to your understanding of the written text), here's a sentence from the language spec:

    If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body is implicitly assumed by the compiler to begin with a super class constructor invocation “super();”, an invocation of the constructor of its direct superclass that takes no arguments.

提交回复
热议问题