java创建一个手机类,其中包含私有属性品牌、型号和价格,然 后创建方法去访问和修改这些属性的测试类
时间: 2024-05-03 19:16:34 浏览: 16
下面是一个示例代码,实现了一个手机类(Phone)和一个测试类(TestPhone),用于访问和修改私有属性:
```java
public class Phone {
private String brand;
private String model;
private double price;
public Phone(String brand, String model, double price) {
this.brand = brand;
this.model = model;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
public class TestPhone {
public static void main(String[] args) {
Phone phone = new Phone("Apple", "iPhone X", 999.99);
System.out.println("Brand: " + phone.getBrand());
System.out.println("Model: " + phone.getModel());
System.out.println("Price: " + phone.getPrice());
phone.setBrand("Samsung");
phone.setModel("Galaxy S10");
phone.setPrice(899.99);
System.out.println("Brand: " + phone.getBrand());
System.out.println("Model: " + phone.getModel());
System.out.println("Price: " + phone.getPrice());
}
}
```
在测试类中,我们首先创建了一个手机对象(Phone),并使用对象的访问器方法(getBrand()、getModel()、getPrice())获取私有属性的值。然后,我们使用对象的修改器方法(setBrand()、setModel()、setPrice())修改私有属性的值,并再次使用访问器方法获取新的值。