このJavaキーワードのガイド
1. 前書き
このチュートリアルでは、we’ll take a look at the this Java keyword.
Javaでは、this keyword is a reference to the current object whose method is being called。
キーワードをいつどのように使用できるかを見てみましょう。
2. フィールドシャドウイングの明確化
The keyword is useful for disambiguating instance variables from local parameters。 最も一般的な理由は、インスタンスフィールドと同じ名前のコンストラクタパラメータがある場合です。
public class KeywordTest {
private String name;
private int age;
public KeywordTest(String name, int age) {
this.name = name;
this.age = age;
}
}
ここに表示されているように、nameおよびageインスタンスフィールドでthisを使用して、パラメータと区別しています。
もう1つの使用法は、ローカルスコープでパラメータを非表示またはシャドウイングするthisを使用することです。 使用例は、Variable and Method Hidingの記事にあります。
3. 同じクラスのコンストラクターを参照する
From a constructor, we can use this() to call a different constructor of the same class。 ここでは、コンストラクタチェーンにthis()を使用して、コードの使用量を減らしています。
最も一般的な使用例は、パラメーター化されたコンストラクターからデフォルトコンストラクターを呼び出すことです。
public KeywordTest(String name, int age) {
this();
// the rest of the code
}
または、引数なしのコンストラクタからパラメータ化されたコンストラクタを呼び出して、いくつかの引数を渡すことができます。
public KeywordTest() {
this("John", 27);
}
this()をコンストラクターの最初のステートメントにする必要があることに注意してください。そうしないと、コンパイルエラーが発生します。
4. パラメータとしてthisを渡す
ここにprintInstance()メソッドがあり、this Keyword引数が定義されています。
public KeywordTest() {
printInstance(this);
}
public void printInstance(KeywordTest thisKeyword) {
System.out.println(thisKeyword);
}
コンストラクター内で、printInstance()メソッドを呼び出します。 thisを使用して、現在のインスタンスへの参照を渡します。
5. thisを返す
メソッドからのWe can also use this keyword to return the current class instance。
コードを複製しないために、builder design patternでコードがどのように実装されているかの完全な実用例を次に示します。
6. 内部クラス内のthisキーワード
また、thisを使用して、内部クラス内から外部クラスインスタンスにアクセスします。
public class KeywordTest {
private String name;
class ThisInnerClass {
boolean isInnerClass = true;
public ThisInnerClass() {
KeywordTest thisKeyword = KeywordTest.this;
String outerString = KeywordTest.this.name;
}
}
}
ここで、コンストラクター内で、KeywordTest.this呼び出し.を使用してKeywordTestインスタンスへの参照を取得できます。さらに深く掘り下げて、KeywordTest.this.name fieldなどのインスタンス変数にアクセスできます。
7. 結論
この記事では、Javaのthisキーワードについて説明しました。
いつものように、完全なコードはover on Githubで利用できます。