Files
javademos/java25-features/src/FlexibleConstructorDemo.java
T

28 lines
1.3 KiB
Java

/** JEP 513 (final in 25): statements may run before super(...) as long as they do not touch `this`. */
public class FlexibleConstructorDemo {
static class Shape {
final String describe;
Shape() { this.describe = describe(); } // calls an overridden method from the super constructor
String describe() { return "shape"; }
}
static class Square extends Shape {
final int side;
Square(int side) {
if (side <= 0) throw new IllegalArgumentException("side must be positive, got " + side); // before super()
this.side = side; // assigning a field before super() is allowed
super();
}
@Override String describe() { return "square side=" + side; } // sees side, not the default 0
}
static class Old extends Shape {
final int side;
Old(int side) { super(); this.side = side; }
@Override String describe() { return "old square side=" + side; }
}
public static void main(String[] args) {
System.out.println(new Square(4).describe);
System.out.println(new Old(4).describe);
try { new Square(-1); } catch (IllegalArgumentException e) { System.out.println("rejected: " + e.getMessage()); }
}
}