LoginSignup
0
0

More than 5 years have passed since last update.

JAVA setterメソッド

Posted at

getterメソッドとは逆に、ある特定のフィールドに指定された値を単に代入するだけのメソッドをsetterメソッドといいます。

▪️setterメソッドの書き方(定石)
public void setフィールド名(フィールドの型 任意の変数名) {
      return this.フィールド = 任意の変数名;
}

▪️Hero2.java

public void setName(String name) {
        this.name = name;
        System.out.println(this.name);
    }

▪️Main22.java

h.setName("ねこ8");

▪️Hero2.java

public class Hero2 {
    private String name;
    private int hp;
    static int money;
    // Sword2 sword;
    static int money2;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
        System.out.println(this.name);
    }

    Hero2(String name) {
        this.hp = 100;
        this.name = name;
    }

    Hero2() {
        this("ダミー");
    }

    void setRandomMoney() {
        Hero2.money = (int) (Math.random() * 1000);
        System.out.println(name + "たちの所持金を初期化しました");
    }

    public void attack() {
        System.out.println(this.name + "は攻撃した!");
        System.out.println("敵に5ポイントのダメージを与えた!");
    }

    public void attack(Matango2 m) {

    }

    void sleep() {
        this.hp = 100;
        System.out.println(this.name + "は、眠って回復した!");

    }

    void sit(int sec) {
        this.hp += sec;
        System.out.println(this.name + "は、" + sec + "秒座った!");
        System.out.println("HPが" + sec + "ポイント回復した.");

    }

    private void die() {
        System.out.println(this.name + "は死んでしまった!");
        System.out.println("GAME OVERです。");
    }
}

▪️Main22.java


public class Main22 {
    public static void main(String[] args) {
        Hero2 h = new Hero2("ねこ5");
        Hero2 h1 = new Hero2("ミナト");
        Hero2 h2 = new Hero2("ねこ");
        Hero2 h3 = new Hero2("ねこ7");
        h3.sleep();
        h3.sit(4);

        King k = new King();
        k.talk(h);

        System.out.println(h2.getName());
        System.out.println(h3.getName());
        h.setName("ねこ8");
        System.out.println(Hero2.money);
        System.out.println(Hero2.money);
        System.out.println(h1.money);
        System.out.println(Hero2.money);

        Matango2 m1 = new Matango2();
        Matango2 m2 = new Matango2("ねこ3");
        m2.hp = 30;
        System.out.println(m1.name);
        System.out.println(m2.hp);
        System.out.println(m2.name);

    }

}

▪️実行結果
ねこ7は、眠って回復した!
ねこ7は、4秒座った!
HPが4ポイント回復した.
王様:ようこそ我が国へ、勇者ねこ5よ
王様:長旅疲れたであろう。
王様:まずは城下町を見てくるとよい。ではまた会おう。
ねこ
ねこ7
ねこ8
0
0
0
0
ダミー2
30
ねこ3

0
0
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
0
0