用Java中的继承和数组编写一个“已知农产品的质量和体积,判断农产品属于哪类农产品”的代码
时间: 2023-05-14 08:05:58 浏览: 75
以下是Java中继承和数组编写的代码,用于判断农产品属于哪类农产品:
```
public class Agriculture {
private double quality;
private double volume;
public Agriculture(double quality, double volume) {
this.quality = quality;
this.volume = volume;
}
public double getQuality() {
return quality;
}
public double getVolume() {
return volume;
}
}
public class Rice extends Agriculture {
public Rice(double quality, double volume) {
super(quality, volume);
}
}
public class Wheat extends Agriculture {
public Wheat(double quality, double volume) {
super(quality, volume);
}
}
public class AgricultureClassifier {
public static void main(String[] args) {
Agriculture[] products = new Agriculture[4];
products[0] = new Rice(0.8, 1.2);
products[1] = new Wheat(0.7, 1.5);
products[2] = new Rice(0.9, 1.1);
products[3] = new Wheat(0.6, 1.8);
for (Agriculture product : products) {
if (product instanceof Rice) {
System.out.println("This is rice.");
} else if (product instanceof Wheat) {
System.out.println("This is wheat.");
} else {
System.out.println("Unknown product.");
}
}
}
}
```
以上代码中,我们定义了一个Agriculture类,它包含了农产品的质量和体积。然后我们定义了Rice和Wheat类,它们继承了Agriculture类。最后,我们定义了一个AgricultureClassifier类,它包含了一个Agriculture类型的数组,用于存储农产品。我们遍历这个数组,通过instanceof关键字判断每个农产品属于哪个类别。
阅读全文