😸

【Java】クラス

2025/02/16に公開

Javaのクラス(Class)

クラスはオブジェクトを作るための設計図です。
変数(フィールド)メソッド(関数) を持ち、データをまとめて管理できます。


1. クラスの基本

クラスの作成

class クラス名 {
    // フィールド(変数)
    // メソッド(処理)
}

例: Car クラスの作成

class Car {
    String brand;  // フィールド(車のブランド)
    int speed;     // フィールド(速度)

    void drive() { // メソッド(走る動作)
        System.out.println(brand + " is driving at " + speed + " km/h");
    }
}

2. クラスの使い方(オブジェクトの作成)

クラスを使うには、オブジェクト(インスタンス)を作成 します。

例: Car クラスのオブジェクトを作成

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car();  // オブジェクト作成
        myCar.brand = "Toyota"; // フィールドに値をセット
        myCar.speed = 80;
        myCar.drive();          // メソッドを呼び出す
    }
}

✅ 出力:

Toyota is driving at 80 km/h

3. コンストラクタ(初期値をセットする)

コンストラクタはオブジェクト生成時に初期値を設定する特別なメソッドです。

コンストラクタの作成

class Car {
    String brand;
    int speed;

    // コンストラクタ(クラス名と同じ名前)
    Car(String b, int s) {
        brand = b;
        speed = s;
    }

    void drive() {
        System.out.println(brand + " is driving at " + speed + " km/h");
    }
}

コンストラクタを使ったオブジェクト作成

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Honda", 100); // 初期値をセット
        myCar.drive();
    }
}

✅ 出力:

Honda is driving at 100 km/h


まとめ

機能 説明
クラス作成 class クラス名 {}
オブジェクト作成 new クラス名();
フィールド データを保持
メソッド クラスの動作を定義

Discussion