メンバ変数を使ってみる
クラスに登録されているメソッドや変数のことをメンバと呼びます
んで、変数のことをメンバ変数と呼んだりするようです
メンバ変数を使用するには
んで、変数のことをメンバ変数と呼んだりするようです
メンバ変数を使用するには
- クラスの宣言をするときに変数をクラス内で宣言
- オブジェクトを作成
- ばしばし使う
という流れになります
まずはクラスの宣言
//りんごクラス class Apple { int size; //大きさ int cnt; //数 }
オブジェクトを作成
Apple apple0 = new Apple();
メンバ変数にアクセスするには
作成した「オブジェクトの名前.変数名」でアクセスできます
作成した「オブジェクトの名前.変数名」でアクセスできます
apple0.cnt = 10;
サンプル
//りんごクラス class Apple { int size; //大きさ int cnt; //数 } class Sample { public static void main(String args[]) { Apple apple0 = new Apple(); apple0.cnt = 10; apple0.size = 50; System.out.println(apple0.size + "サイズのりんご" + apple0.cnt + "個"); } }