「Java」thisキーワードで自クラスのメソッド(method)やメンバ変数(parameter)を呼出す方法
説明
thisで自クラス内のメソッドやメンバ変数を呼びます。
クラスの定義
package com.arkgame.study;
public class UserInfo {
private String username;
public void callFunc() {
// thisでクラスの変数を呼ぶ
this.username = "Testuser1007";
System.out.println("thisでメンバ変数を呼ぶ結果: " + username);
// thisでクラスのメソットを呼ぶ
String thisRes = this.testFunc();
System.out.println("thisでメソットを呼ぶ結果: " + thisRes);
}
public String testFunc() {
String result;
result = "Message: " + username;
System.out.println("クラスのメンバ変数usernameの値: " + username);
return result;
}
}
thisキーワードを利用するmainクラス
package com.arkgame.study;
public class ThisClassCall {
public static void main(String[] args) {
//UserInfoクラスのオブジェクト宣言
UserInfo userInfo = new UserInfo();
//メソットを呼ぶ
userInfo.callFunc();
}
}
実行結果
thisでメンバ変数を呼ぶ結果: Testuser1007 クラスのメンバ変数usernameの値: Testuser1007 thisでメソットを呼ぶ結果: Message: Testuser1007