下面是一個Java SpareTire類的實例:
public class SpareTire {
private int diameter;
private String brand;
public SpareTire(int diameter, String brand) {
this.diameter = diameter;
this.brand = brand;
}
public int getDiameter() {
return diameter;
}
public void setDiameter(int diameter) {
this.diameter = diameter;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public void inflate() {
System.out.println("Inflating spare tire");
}
public void changeBrand(String newBrand) {
System.out.println("Changing spare tire brand from " + brand + " to " + newBrand);
this.brand = newBrand;
}
public static void main(String[] args) {
// 創建一個SpareTire對象
SpareTire spareTire = new SpareTire(16, "Goodyear");
// 調用對象的方法
System.out.println("Spare tire diameter: " + spareTire.getDiameter());
System.out.println("Spare tire brand: " + spareTire.getBrand());
spareTire.inflate();
spareTire.changeBrand("Michelin");
System.out.println("New spare tire brand: " + spareTire.getBrand());
}
}
這個SpareTire類表示一個備用輪胎,它有一個直徑和品牌屬性,以及一些操作這些屬性的方法。在main方法中,我們創建一個SpareTire對象,并調用它的方法來獲取和修改屬性,并執行一些其他操作。最后,我們打印出修改后的屬性值。