LoginSignup
2
3

More than 5 years have passed since last update.

JAVA-this

Last updated at Posted at 2015-10-21

▪️thisを用いないコード

class ThisTest {
    String name = "Neko2";  // Member Variable
    void meth() {
        String name = "Neko";   // Local Variable
        System.out.println(name);   // 何が出力されますか?
    }
}

▪️実行結果
Neko

結果としては、ローカル変数が優先されます。ここで出力されるのは "Neko" です。

▪️thisを用いるコード

class ThisTest {
    String name = "Neko2";  // Member Variable
    void meth() {
        String name = "Neko";   // Local Variable
        System.out.println(this.name);  // Member Variable
    }
}

▪️実行結果
Neko2

this.name は、「このオブジェクトのメンバー変数 name」 と言う意味です。自クラス内の変数やメソッドを裸で指定していたのは、実は this を省略していたのです。

自分のクラスのメンバーであるメソッドや変数を指定する為には this が使えます。

2
3
0

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
2
3