LoginSignup
4
4

More than 5 years have passed since last update.

this()の引数内でthisキーワードを使用することができない

Last updated at Posted at 2016-01-24

Java SE8 Silverの範囲


例えば以下のようなソースはコンパイルエラーとなる。

class Sample{
  int num;

  Sample(){
    this(this.num);
    this.num = 10;
  }
  Sample(int num){
    this.num = num;
  }
}

白本ではしれっとthis()の引数中ではthisは使えないとか書いてあって解説もなく、不親切だった。
理由は単純で以下のとおりだろう。

実行順序の問題

this.numを呼び出すためには、クラスが初期化されている必要がある。しかしながら初期化を使用とするとthis(this.num)の呼び出しがある。this()を呼び出すためにはthis.numが初期化されている必要があり(正確にはthisがメモリ上に展開されている必要があり)、コンストラクタを呼び出す事もできず、this.numを特定することもできず、コンパイルエラーになってしまう。というところだろう。

これらについて記載された情報があれば教えて頂きたい。

追記

コメントにて公式docから該当箇所を頂いた。
https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.8.7.1
https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.1.3

An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods or inner classes declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs.

このクラスまたはスーパークラスで宣言されたインスタンスメソッドやインスタンス変数にはアクセスできない。また、thisやsuperを使うこともできない。
という感じだろうか…。英語力の無さを恨む

4
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4