問題一覧に戻る
中級オブジェクト指向
問題48: インスタンス変数

インスタンス変数(フィールド)は各オブジェクト固有のデータを格納します。クラスレベルで宣言され、オブジェクトの生存期間中存在します。

public class Car {
// インスタンス変数
String model;
int year;
private double price;

public Car(String m, int y, double p) {
model = m;
year = y;
price = p;
}

public void showInfo() {
System.out.println(model + " (" + year + ") - $" + price);
}

public static void main(String[] args) {
Car car1 = new Car("Tesla", 2023, 45000);
Car car2 = new Car("Toyota", 2022, 30000);

car1.showInfo();
car2.showInfo();
}
}