class Demo{
private c a;
public Demo(c a){
this.a=a;
}
public c getA(){
return a;
}
public void setA(c a){
this.a=a;
}
}
public class Generic {
public static void main(String args[]){
Demo b=new Demo(5);
//b.setA();
System.out.print(b.getA());
}
}
尴尬,前面乱了
重写遍
int是基本类型,你换成Integer就好了
Demo b=new Demo<>(5);
定义类的时候:
class Demo{
//这里是你的那些代码
}
使用的时候在main函数中
Demo demo=new Demo(5);
我没测试,你试试
泛型<>里边必须是对象类型,你这报错是由于<>里边是基本类型导致的。
同意楼上的,你可以试一下
泛型类型必须是引用类型,换成
int是基本类型,换成Integer
Demo new Demo<>(a);
public class Demo<E> {
private E a;
public Demo(E a){
this.a=a;
}
public E getA(){
return a;
}
public void setA(E a){
this.a=a;
}
}
差不多像这种感觉?
Generic.java文件代码如下:
class Demo<T> {
private T a;
public Demo(T a) {
this.a = a;
}
public T getA() {
return a;
}
public void setA(T a) {
this.a = a;
}
}
public class Generic {
public static void main(String args[]) {
Demo<Integer> integerBox = new Demo<Integer>(5);
Demo<String> stringBox = new Demo<String>("Hello");
System.out.printf("Integer Value :%d\n", integerBox.getA());
System.out.printf("String Value :%s\n\n", stringBox.getA());
integerBox.setA(new Integer(10));
stringBox.setA(new String("Hello World"));
System.out.printf("New Integer Value :%d\n", integerBox.getA());
System.out.printf("New String Value :%s\n", stringBox.getA());
}
}
说明:
1 泛型类的写法有规定语法。
2 参数应为引用类型。
测试结果如下图:
应该是Integer