4 ms·
this() and super() MUST be called during the Initialization Block, which MAY include guard / error tests and variable assignments (a list of permitted actions a
by mjevans 4y ago
this() and super() MUST be called during the Initialization Block, which MAY include guard / error tests and variable assignments (a list of permitted actions and types of actions is more complex).
- TylerE 4y agoThey aren’t mandatory, no? Thus must, or especially “MUST” is misleading.
- josephcsible 4y agoThis is the slightly confusing part: a call to another constructor is mandatory, but if you don't call any other constructors yourself, super() automatically gets called before your code, without you having to write it.
- mjevans 4y agoYeah, that's the confusing part. Historically that segment of code, much like version of other languages that require variable declaration only at the start of a new scope, is just implicitly at the start. There isn't a linguistic structure that separates it from more normal code that does other tasks; previously it was a compiler error.
- tsimionescu 4y agoThey may be ellided entirely if there is a superclass constructor without any parameters. In all other cases, either super(...) or this(...) MUST be called exactly once. Additionally, you can't catch Exceptions thrown by a call to super(...) or this(...) (so you can't call them inside a try{} block). Finally, you can't reference any non-static members of the "this" object except to write to write to a field. So yes, the rule is significantly more complex.