S-JIS[2024-03-22] 変更履歴
Java22のsuper()・this()の前に文を書けるようにする緩和(プレビュー版)について。
2024/3/19にリリースされたJava22で、プレビュー版としてsuper()・this()の前に文が書けるようになった。
親コンストラクター呼び出し(super())や代替コンストラクター呼び出し(this())の前に文を書くことが出来る。
ただし、そこでは、初期化されていない領域にはアクセスできない。(コンパイルエラーになる)
すなわち、親クラス・自クラスのインスタンスフィールドにはアクセスできない。
thisそのものを使用することも出来ない。
super()・this()の前に文を書くのはJava22ではプレビュー版の機能なので、この機能を使いたい場合はコンパイル時にjavacコマンドに--enable-previewを付ける必要があり、
また、実行時にjavaコマンドに--enable-previewを付ける必要がある。
JShellで試す場合もjshellコマンドに--enable-previewを付ける。
> javac --enable-preview --release 22 Example.java > java --enable-preview Example
> java --enable-preview --source 22 Example.java
super()・this()の呼び出し前に値をチェックする例。
public class PositiveBigInteger extends BigInteger {
public PositiveBigInteger(long value) {
if (value <= 0) {
throw new IllegalArgumentException("non-positive value");
}
super(value);
}
}
super()・this()の呼び出し前に計算を行う例。
public class Example {
public Example(String s) {
String key, value;
int n = s.indexOf("=");
if (n >= 0) {
key = s.substring(0, n);
value = s.substring(n + 1);
} else {
key = s;
value = null;
}
this(key, value);
}
public Example(String key, String value) {
〜
}
}
super()・this()の呼び出しの前にthisを使うとコンパイルエラーになる。
public class Example { public Example(int n) { System.out.println(this); // NG this(); } public Example() { } }