Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, is it possible for a super constructor invocation actually invoke a constructor in the calling class?

Super constructor invocation definition:

[Primary.] [NonWildTypeArguments] super ( ArgumentListopt ) ;

A super constructor call can be prefixed by an Primary expression. Example (taken from JLS):

class Outer {
    class Inner{ }
}

class ChildOfInner extends Outer.Inner {
    ChildOfInner() {
        (new Outer()).super(); // (new Outer()) is the Primary
    }
}

Does a Primary expression exist that makes the call to super() the invocation of a constructor of the calling class? Or Java prevents that?

like image 897
John Assymptoth Avatar asked Jan 26 '26 09:01

John Assymptoth


1 Answers

Does a Primary expression exist that makes the call to super() the invocation of a constructor of the calling class?

No. There is no way to divert the super() call be the equivalent of using this(). The sole reason for Primary is to provide the instantiating outer context when the superclass is a non-static inner class.

The Primary expression is not selecting a constructor or class - its just passing context information required by some constructors (i.e. the outer instance required by an non-static inner class).

Edit:

The OP asks for a source. I don't have one - I basing this answer solely on my reading of the spec, which I think is pretty clear:

... the keyword super ... used to invoke a constructor of the direct superclass.

If the superclass constructor invocation is qualified, then the Primary expression p immediately preceding ".super" is ... the immediately enclosing [outer] instance ... it is a compile-time error if the type of p is not O [outer class] or a subclass of O.

If there's a qualifying expression on super, it can only be used to return an instance of the enclosing class of the superclass (or an instance of a subclass of the enclosing class of the superclass). The qualifying expression has no bearing on which class' constructor is called in response to super(), i.e. there is no value that the qualifying expression can return that will change which class whose constructor is to be invoked as super() - super() will always invoke a constructor of the direct superclass.

like image 92
Bert F Avatar answered Jan 27 '26 22:01

Bert F



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!