java创建一个水果类,其中包含私有属性名称、价格和重量,然 后创建方法去访问和修改这些属性的测试类
时间: 2024-04-30 11:18:05 浏览: 69
Python 类的私有属性和私有方法实例分析
以下是Java创建一个水果类,并包含私有属性名称、价格和重量,以及访问和修改这些属性的测试类的示例代码:
```java
public class Fruit {
private String name;
private double price;
private double weight;
public Fruit(String name, double price, double weight) {
this.name = name;
this.price = price;
this.weight = weight;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public double getWeight() {
return weight;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
public void setWeight(double weight) {
this.weight = weight;
}
}
public class FruitTest {
public static void main(String[] args) {
Fruit apple = new Fruit("Apple", 1.99, 0.3);
System.out.println("Name: " + apple.getName());
System.out.println("Price: $" + apple.getPrice());
System.out.println("Weight: " + apple.getWeight() + "kg");
apple.setPrice(2.49);
System.out.println("Updated Price: $" + apple.getPrice());
apple.setWeight(0.4);
System.out.println("Updated Weight: " + apple.getWeight() + "kg");
apple.setName("Red Apple");
System.out.println("Updated Name: " + apple.getName());
}
}
```
运行结果如下:
```
Name: Apple
Price: $1.99
Weight: 0.3kg
Updated Price: $2.49
Updated Weight: 0.4kg
Updated Name: Red Apple
```
阅读全文