「Java」thisキーワードで自クラスのメソッド(method)やメンバ変数(parameter)を呼出す方法

2020年10月28日

説明
thisで自クラス内のメソッドやメンバ変数を呼びます。
クラスの定義

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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;
}
}
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; } }
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クラス

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
public class ThisClassCall {
public static void main(String[] args) {
//UserInfoクラスのオブジェクト宣言
UserInfo userInfo = new UserInfo();
//メソットを呼ぶ
userInfo.callFunc();
}
}
package com.arkgame.study; public class ThisClassCall { public static void main(String[] args) { //UserInfoクラスのオブジェクト宣言 UserInfo userInfo = new UserInfo(); //メソットを呼ぶ userInfo.callFunc(); } }
package com.arkgame.study;

public class ThisClassCall {

      public static void main(String[] args) {
            
            //UserInfoクラスのオブジェクト宣言
            UserInfo userInfo = new UserInfo();
            //メソットを呼ぶ
            userInfo.callFunc();

      }

}

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
thisでメンバ変数を呼ぶ結果: Testuser1007
クラスのメンバ変数usernameの値: Testuser1007
thisでメソットを呼ぶ結果: Message: Testuser1007
thisでメンバ変数を呼ぶ結果: Testuser1007 クラスのメンバ変数usernameの値: Testuser1007 thisでメソットを呼ぶ結果: Message: Testuser1007
thisでメンバ変数を呼ぶ結果: Testuser1007
クラスのメンバ変数usernameの値: Testuser1007
thisでメソットを呼ぶ結果: Message: Testuser1007

 

Java

Posted by arkgame