diff --git a/JavaReleases/src/test/java/pl/mperor/lab/java/Java25.java b/JavaReleases/src/test/java/pl/mperor/lab/java/Java25.java index 746a43d..150dc8d 100644 --- a/JavaReleases/src/test/java/pl/mperor/lab/java/Java25.java +++ b/JavaReleases/src/test/java/pl/mperor/lab/java/Java25.java @@ -38,4 +38,64 @@ public void testPrintFromIOClass() { TestUtils.resetSystemOut(); } -} \ No newline at end of file + @Test + public void testValidateArgumentBeforeSuperCall() { + Assertions.assertEquals(5, new PositiveBox(5).value); + Assertions.assertThrows(IllegalArgumentException.class, () -> new PositiveBox(-1)); + } + + static class Box { + final int value; + + Box(int value) { + this.value = value; + } + } + + /// Before JEP 513, validating/transforming `value` required a private static + /// helper method invoked inside `super(...)`, since no statement could precede it. + static class PositiveBox extends Box { + PositiveBox(int value) { + if (value <= 0) { + throw new IllegalArgumentException("value must be positive: " + value); + } + super(value); + } + } + + @Test + public void testFieldAssignedBeforeSuperVisibleToOverriddenMethod() { + var circle = new Circle(2.5); + Assertions.assertEquals("circle r=2.5", circle.description); + } + + static class Shape { + Shape() { + describe(); // an overridable method invoked from the superclass constructor + } + + void describe() { + } + } + + static class Circle extends Shape { + final double radius; + String description; + + Circle(double radius) { + // Still forbidden in the prologue (would not compile here, before super()): + // System.out.println(this); // cannot reference `this` + // describe(); // cannot call an instance method + // System.out.println(radius); // cannot read an own field back + this.radius = radius; // JEP 513: assigning an own field is now allowed before super() + super(); + } + + @Override + void describe() { + // radius is already set here, even though super() has not returned yet + description = "circle r=" + radius; + } + } + +}