编程题:定义一个泛型类Apple,有一个weight属性,编写没有参数的构造方法和有参数的构造方法,定义它的set方法和get方法。在主类的main方法中,实例化不同的泛型对象a1,a2,a3,要求对象a1的weight属性是String类型,要求对象a2的weight属性是Integer类型,要求对象a3的weight属性是Double类型,它们的值分别是“500克”,500,500.5,调用get方法输出各对象的weight的值。运行结果如图所示。
时间: 2023-11-27 10:55:18 浏览: 70
```java
public class Apple<T> {
private T weight;
public Apple() {
}
public Apple(T weight) {
this.weight = weight;
}
public T getWeight() {
return weight;
}
public void setWeight(T weight) {
this.weight = weight;
}
public static void main(String[] args) {
Apple<String> a1 = new Apple<>("500克");
System.out.println("a1的重量:" + a1.getWeight());
Apple<Integer> a2 = new Apple<>(500);
System.out.println("a2的重量:" + a2.getWeight());
Apple<Double> a3 = new Apple<>(500.5);
System.out.println("a3的重量:" + a3.getWeight());
}
}
```
输出结果:
```
a1的重量:500克
a2的重量:500
a3的重量:500.5
```
阅读全文