Question 1: To develop a generic Apple class, a weight attribute weight is required to instantiate different generic objects in the test class. This attribute of object a1 is required to be of type String, and this attribute of object a2 is of type Integer. This attribute of a3 is of Double type. Assign values to the weight attributes of a1, a2, and a3: "500 grams", 500, 500.0, and call the accessor to get the attribute value and output it in the test class.
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());
}
}
The second question: define a generic interface, which has an eat method. Use a Person class to implement this interface, the incoming generic argument is of type String, the content of the implemented method is defined by yourself, and finally the eat method is called in main.
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);
}
}