共計 648 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用以下方式定義一個 Vehicle 類:
public class Vehicle {// 定義屬性
private String brand;
private int year;
// 定義構造方法
public Vehicle(String brand, int year) {this.brand = brand;
this.year = year;
}
// 定義方法
public void start() {System.out.println("The vehicle starts.");
}
public void stop() {System.out.println("The vehicle stops.");
}
// 定義 getter 和 setter 方法
public String getBrand() {return brand;
}
public void setBrand(String brand) {this.brand = brand;
}
public int getYear() {return year;
}
public void setYear(int year) {this.year = year;
}
}
在上述代碼中,定義了一個名為 Vehicle 的類。它有兩個私有屬性:brand(品牌)和 year(年份)。通過構造方法可以初始化這些屬性值。類中還定義了 start 和 stop 方法,用于啟動和停止車輛。同時,還提供了 getter 和 setter 方法,用于獲取和設置屬性的值。
你可以根據具體的需求,繼續在 Vehicle 類中添加其他屬性和方法。
丸趣 TV 網 – 提供最優質的資源集合!
正文完