用Java>设计一个Fruit类,一个Test Fruit类。要求如下: r Fruit类中包含产地area、季节season、价格price三个属性; >分别给这三个属性定义两个方法(设计对价格进行判断),一个方法用于设置值 setName(),一个方法用于获取值getName(); >定义一个无参构造方法,一个接收三个参数的构造方法,三个参数分别为产地、季节、价格属性赋值; >定义say()方法,对水果做自我介绍; 在测试类中创建两个Fruit对象,一个使用无参的构造方法,一个使用有参的构造方法,在构造方法中给姓名和成绩赋值。 请思考,如何用封装的思想定义构造方法,可参考教材实例3-4
时间: 2023-04-10 14:04:48 浏览: 110
好的,我明白了,我将扮演一个由 CSDN 开发的 C 知道,我会尽力回答您的问题。关于您的第一个问题,以下是 Java 中 Fruit 类和 TestFruit 类的代码:
```java
public class Fruit {
private String area;
private String season;
private double price;
public Fruit() {}
public Fruit(String area, String season, double price) {
this.area = area;
this.season = season;
setPrice(price);
}
public void setArea(String area) {
this.area = area;
}
public String getArea() {
return area;
}
public void setSeason(String season) {
this.season = season;
}
public String getSeason() {
return season;
}
public void setPrice(double price) {
if (price < 0) {
System.out.println("价格不能为负数!");
return;
}
this.price = price;
}
public double getPrice() {
return price;
}
public void say() {
System.out.println("我是一种水果,产地在" + area + ",季节在" + season + ",价格为" + price + "元。");
}
}
public class TestFruit {
public static void main(String[] args) {
Fruit fruit1 = new Fruit();
fruit1.setArea("中国");
fruit1.setSeason("夏季");
fruit1.setPrice(5.0);
Fruit fruit2 = new Fruit("美国", "冬季", 8.0);
fruit1.say();
fruit2.say();
}
}
```
在 Fruit 类中,我们使用了封装的思想,将属性设置为私有的,通过公有的 set 和 get 方法来访问属性。在 setPrice 方法中,我们对价格进行了判断,如果价格为负数,则输出错误信息。在 say 方法中,我们对水果进行了自我介绍。
在 TestFruit 类中,我们创建了两个 Fruit 对象,一个使用无参构造方法,一个使用有参构造方法,并分别给属性赋值。最后,我们调用 say 方法,让水果进行自我介绍。
希望我的回答能够帮助到您!
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)