LoginSignup
1
0

More than 3 years have passed since last update.

java(クラスとインスタンス)

Last updated at Posted at 2020-05-16

定数フィールドの宣言

public class Matango {
    int hp;
    //int level = 10;    //フィールド
    final int LEVEL = 10; //定数フィールド
}

値を書き換えることができないようにする定数フィールド
finalを付けて名前を大文字にする(LEVEL)

thisは省略しない

public class Hero {
    String name;   //名前の宣言
    int hp;        //HPの宣言

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

this.は省略しても動作する
ローカル変数や引数にも同じhpがあるとそちらが優先されてしまう可能性がある
フィールドを用いる時はthis.をつけるようにする

インスタンスの生成

public class Main {
    public static void main(String[] args) {
        //1、勇者を生成
        Hero h = new Hero();
    }
}

クラス名(Hero) 変数名(h) = new クラス名(Hero)();

フィールドへの値の代入

public class Main {
    public static void main(String[] args) {
        //1、勇者を生成
        Hero h = new Hero();
        //2、フィールドに初期値をセット
        h.name = "勇者";
        h.hp = 100;
        System.out.println("勇者" + h.name + "を生み出しました!");
    }
}

変数名.(h.) フィールド名(name) = 値("勇者");

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