4 ms·
I think this change would make it harder to explain why a program was rejected, even though it would allow a programmer more flexibility. It's easier to just s
by rustyminnow 4y ago
I think this change would make it harder to explain why a program was rejected, even though it would allow a programmer more flexibility.
It's easier to just say "this() must ALWAYS be called first in constructor" and everybody understands... than to try and say "you can call this() after other statements, but not in a try block and not if those statements reference the instance under construction" which will certainly allow you to do more interesting things, but also be more confusing.
- mjevans 4y agothis() 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.
- nayuki 4y ago"this() must always be called first in the constructor" is not true! Consider the following example: Foo(long x) { ... } Foo(double y) { this(Math.round(y)); } In the second constructor, the first call is Math.round(), followed by Foo(int). I am talking about evaluation order, not lexical order. I found myself needing to work around the limitation recently: https://github.com/nayuki/PNG-library/blob/b92cedc23b1fc32d51bbc528797b9b55eba6bc17/src/io/nayuki/png/chunk/Gama.java#L36-L49 https://github.com/nayuki/PNG-library/blob/b92cedc23b1fc32d5...