能否提供一份用Java编写的水果品质分级技术相关的代码示例?
时间: 2024-10-23 09:12:51 浏览: 22
在Java中,我们可以创建一个水果抽象类和一些具体的子类来体现多态的特性,并根据某种标准对水果进行品质分级。这里是一个简单的示例:
```java
// 抽象的水果类
public abstract class Fruit {
protected String name;
protected int quality;
public Fruit(String name) {
this.name = name;
}
// 抽象的评级方法
public abstract String grade();
public String getName() {
return name;
}
}
// 具体的苹果类,实现抽象方法
public class Apple extends Fruit {
private int colorRating;
private int sizeRating;
public Apple(String name, int colorRating, int sizeRating) {
super(name);
this.colorRating = colorRating;
this.sizeRating = sizeRating;
}
@Override
public String grade() {
if (colorRating >= 8 && sizeRating >= 7) {
return "优质";
} else if (colorRating >= 6 && sizeRating >= 5) {
return "良好";
} else {
return "一般";
}
}
}
// 具体的香蕉类,同样实现抽象方法
public class Banana extends Fruit {
private int ripenessRating;
public Banana(String name, int ripenessRating) {
super(name);
this.ripenessRating = ripenessRating;
}
@Override
public String grade() {
if (ripenessRating == 10) {
return "完美";
} else if (ripenessRating >= 8) {
return "成熟";
} else {
return "未熟";
}
}
}
// 测试部分
public class Main {
public static void main(String[] args) {
Fruit apple = new Apple("红富士", 9, 7);
Fruit banana = new Banana("金蕉", 8);
System.out.println(apple.getName() + "'s grade is: " + apple.grade());
System.out.println(banana.getName() + "'s grade is: " + banana.grade());
}
}
```
在这个例子中,`Apple`和`Banana`类都实现了`Fruit`类的`grade`方法,根据各自的评分标准来决定水果的品质等级。
阅读全文