第一题:开发一个泛型Apple类,要求有一个重量属性weight在测试类中实例化不同的泛型对象,要求对象a1的这一属性是String类型,对象a2的这一属性是Integer型,a3的这一属性是Double型。分别为a1,a2,a3的重量属性赋值为:”500克”,500,500.0,在测试类中通过对象调用访问器得到属性值并输出。
public class Apple<T> {
private T weight;
public T getWeight() {
return weight;
}
public void setWeight(T weight) {
this.weight = weight;
}
public Apple(T weight) {
this.weight = weight;
}
public Apple() {
}
@Override
public String toString() {
return "Apple{" +
"weight=" + weight +
'}';
}
}
//测试类
public class AppleDemo {
public static void main(String[] args) {
Apple<String> a1= new Apple<>("500克");
Apple<Integer> a2 = new Apple<>(500);
Apple<Double> a3 = new Apple<>(500.0);
System.out.println("a1的重量:"+a1.getWeight());
System.out.println("a2的重量:"+a2.getWeight());
System.out.println("a3的重量:"+a3.getWeight());
}
}
第二题:自己定义一个泛型接口,其中有一个eat方法。用一个Person类实现这个接口,传入的泛型实参是String类型,实现的方法内容自己定义,最后在main中调用eat方法。
public interface Demo<T>{
public T eat(T t);
}
class person implements Demo<String>{
@Override
public String eat(String s) {
return s;
}
}
public class Demo01 {
public static void main(String[] args) {
Demo<String> demo = new person();
String str = demo.eat("吃饭");
System.out.println(str);
}
}