Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 61 additions & 1 deletion JavaReleases/src/test/java/pl/mperor/lab/java/Java25.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,64 @@ public void testPrintFromIOClass() {
TestUtils.resetSystemOut();
}

}
@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;
}
}

}
Loading