在java语言中用继承,数组写一个“已知某个农产品的质量和体积,判断农产品属于哪类农产品”的代码
时间: 2023-05-13 21:07:16 浏览: 107
用java编写的有关继承的程序
以下是Java语言中用继承、数组写一个“已知某个农产品的质量和体积,判断农产品属于哪类农产品”的代码:
```
class AgriculturalProduct {
double quality;
double volume;
String type;
public AgriculturalProduct(double quality, double volume) {
this.quality = quality;
this.volume = volume;
}
public String getType() {
return type;
}
}
class Rice extends AgriculturalProduct {
public Rice(double quality, double volume) {
super(quality, volume);
this.type = "rice";
}
}
class Wheat extends AgriculturalProduct {
public Wheat(double quality, double volume) {
super(quality, volume);
this.type = "wheat";
}
}
class Corn extends AgriculturalProduct {
public Corn(double quality, double volume) {
super(quality, volume);
this.type = "corn";
}
}
public class Main {
public static void main(String[] args) {
AgriculturalProduct[] products = new AgriculturalProduct[3];
products[0] = new Rice(0.8, 1.2);
products[1] = new Wheat(0.7, 1.5);
products[2] = new Corn(0.6, 1.8);
double quality = 0.7;
double volume = 1.3;
for (AgriculturalProduct product : products) {
if (quality == product.quality && volume == product.volume) {
System.out.println("This agricultural product is " + product.getType());
break;
}
}
}
}
```
以上代码中,我们定义了一个AgriculturalProduct类,其中包含了农产品的质量和体积,并定义了一个getType()方法,用于获取农产品的类型。然后,我们定义了Rice、Wheat和Corn三个类,分别继承自AgriculturalProduct类,并在构造函数中设置了对应的类型。最后,在Main类中,我们定义了一个AgriculturalProduct类型的数组,用于存储三种不同的农产品,然后根据输入的质量和体积,遍历数组,找到对应的农产品类型并输出。
阅读全文