学生の名前と点数を一緒に管理したいとき、変数を2つずつ並べるのは大変です。クラスを使うと、関連するデータをひとまとめにして「Student」のような名前で扱えるようになります。
この回は VS Code とローカルの Java 環境を使います。まだ準備ができていなければ、先にVS Code で Java を書く準備を済ませてください。
バラバラの変数だと何が困るか
学生3人分の名前と点数を変数で管理してみます。
public class Main {
public static void main(String[] args) {
String name1 = "田中";
int score1 = 80;
String name2 = "佐藤";
int score2 = 70;
String name3 = "鈴木";
int score3 = 90;
System.out.println(name1 + ": " + score1 + "点");
System.out.println(name2 + ": " + score2 + "点");
System.out.println(name3 + ": " + score3 + "点");
}
}
田中: 80点
佐藤: 70点
鈴木: 90点
name1 と score1 が同じ学生のデータだという対応は、プログラマが頭の中で管理しています。人数が増えると変数の組み合わせを間違えやすくなります。
クラスでまとめる
「名前と点数をセットで持つもの」をクラスとして定義します。
public class Main {
public static void main(String[] args) {
Student s = new Student("田中", 80);
System.out.println(s.name + ": " + s.score + "点");
}
}
class Student {
String name;
int score;
Student(String name, int score) {
this.name = name;
this.score = score;
}
}
田中: 80点
新しい要素がいくつか出てきました。
| 要素 | コード | 意味 |
|---|---|---|
| クラス | class Student { ... } | 「Student とは何か」を定義する |
| フィールド | String name; / int score; | クラスが持つデータ |
| コンストラクタ | Student(String name, int score) | オブジェクトを作るときに呼ばれる |
this.name | this.name = name; | 「このオブジェクト自身」のフィールドに値を入れる |
コンストラクタはメソッドに似ていますが、戻り値の型がなく、クラス名と同じ名前です。
オブジェクトを作る
new Student("田中", 80) が、Student クラスの設計図をもとに実体(オブジェクト)を1つ作る操作です。
Student クラス(設計図)
├── name: String
└── score: int
new Student("田中", 80) → オブジェクト s
├── name: "田中"
└── score: 80
設計図は1つですが、new するたびに別のオブジェクトを作れます。
複数のオブジェクトを作る
同じクラスから、データの違うオブジェクトをいくつでも作れます。
public class Main {
public static void main(String[] args) {
Student s1 = new Student("田中", 80);
Student s2 = new Student("佐藤", 70);
Student s3 = new Student("鈴木", 90);
System.out.println(s1.name + ": " + s1.score + "点");
System.out.println(s2.name + ": " + s2.score + "点");
System.out.println(s3.name + ": " + s3.score + "点");
}
}
class Student {
String name;
int score;
Student(String name, int score) {
this.name = name;
this.score = score;
}
}
田中: 80点
佐藤: 70点
鈴木: 90点
冒頭のバラバラの変数と出力結果は同じですが、s1.name と s1.score がセットであることがコード上で明確になりました。
クラスにメソッドを追加する
Student クラスに「自己紹介」するメソッドを追加します。
public class Main {
public static void main(String[] args) {
Student s1 = new Student("田中", 80);
Student s2 = new Student("佐藤", 70);
s1.introduce();
s2.introduce();
}
}
class Student {
String name;
int score;
Student(String name, int score) {
this.name = name;
this.score = score;
}
void introduce() {
System.out.println(name + "です。" + score + "点でした。");
}
}
田中です。80点でした。
佐藤です。70点でした。
introduce メソッドは Student クラスの中に書いたので、s1.introduce() のように呼び出します。メソッドの中では name や score はそのオブジェクト自身のフィールドを指します。
これまで static を付けていたメソッドとの違いは、「どのオブジェクトのデータを使うか」が呼び出し元で決まる点です。s1.introduce() は田中のデータ、s2.introduce() は佐藤のデータを使います。
この時点での Student クラスの構成をまとめます。
classDiagram
class Student {
String name
int score
Student(String name, int score)
void introduce()
}
次の回へ
次は、ArrayList とクラスを組み合わせて「オブジェクトの一覧を扱う」方法を見ます。Student の配列やリストを for 文で回すと、データの管理がさらに整理されます。