3 ms·
JEP 447: Statements before super()
- PaulHoule 4y agoI have wanted this so bad from the days of JDK 1.0
- kiwijamo 4y agoCan you give an example of how this could be used?
- xmcqdpt2 4y agoThe simplest example is just calculating default values that aren't trivial, class X { X(Thing y) {...} X() { var y = ... ... do some more stuff ... this(y); } } This is currently possible using static functions but it can often end up a bit harder to read.
- oweiler 4y agoNever had a need for this. static factory methods are almost always the better solutions. Ctors should only assign params to fields and nothing more. Though I applaud that it makes the language more intuitive/consistent.
- BlackFly 4y agoI would often use static factory methods as well (next to the other patterns given in the JEP itself), but it breaks the usual convention of using new, so it adds a bit of cognitive load to learning an API where you expect to be able to use new, nope that's private, so you try build(), construct(), etc. before finally reading the documents to figure out what the name of the static method is, oh it's initialize(). Constructors in java should enforce class invariants in my opinion. Otherwise we should just have data only record initializers like the new record classes have. I expect a constructor for BigPositiveInteger to never be able to construct a negative integer.
- nh23423fefe 4y agoNo. Constructors turn argument lists into instances. You can't find a "should" anywhere.
- exabrial 4y agoPrior to this JEP I always thought there was some big mystery reason in the JVM why this wasn’t allowed. I would possibly guess the original authors were trying to maintain consistent lock acquisition ordering. Turns out it was “just because” (Not always a bad thing, but maybe a bit over restrictive here).