. 編马程宇模拟两个村庄共用一口井水。编写一个Village 类,该类有一个静态的 int 型成品变量 waterAmount,用于模拟井水的水量。在玉类 Land 的main()方法中创建两个村庄, —个村庄改变了 waterAmount 的值,另一个村庄查看 waterAmaunt 的值。 注程序运行效果:。 I* 水井串有200水 赵庄喝了50升水 刘庄发现水井中有150升水 赵庄人口:80 刘庄人口:120 (40分)+
时间: 2024-03-14 14:42:53 浏览: 29
好的,以下是Java代码实现:
```java
public class Village {
public static int waterAmount = 200; // 初始化井水的水量为200升
public int population; // 村庄的人口数
public Village(int population) {
this.population = population;
}
public static void main(String[] args) {
Village zhao = new Village(80);
Village liu = new Village(120);
zhao.drinkWater(50); // 赵庄喝了50升水
System.out.println("赵庄人口:" + zhao.population + ",刘庄发现水井中有" + waterAmount + "升水");
System.out.println("刘庄人口:" + liu.population + ",刘庄发现水井中有" + waterAmount + "升水");
}
public void drinkWater(int amount) {
waterAmount -= amount; // 减少井水的水量
}
}
```
输出结果为:
```
赵庄人口:80,刘庄发现水井中有150升水
刘庄人口:120,刘庄发现水井中有150升水
```
解释一下代码逻辑:
首先定义一个`Village`类,该类有一个静态的`waterAmount`变量,用于存储井水的水量,以及一个实例变量`population`,用于存储村庄的人口数。
在`main`方法中,先创建两个村庄`zhao`和`liu`,分别设置它们的人口数为80和120。
然后,调用`zhao`的`drinkWater`方法,传入参数50,表示赵庄喝了50升水。在`drinkWater`方法中,将`waterAmount`减去喝水的量。
最后,输出两个村庄的人口数和水井中的水量。
需要注意的是,`waterAmount`是静态变量,可以被所有实例共享,所以任何一个村庄改变了`waterAmount`的值,其他村庄都能够看到这个变化。