62,614
社区成员
发帖
与我相关
我的任务
分享
interface A<T>
{
public String fun(T t);
};
class B implements A<B>
{
private String info;
public B(String info){
this.info = info;
}
public String fun(B b){
return this.info + b.info;
}
};
public class Demo
{
@SuppressWarnings("unchecked")
public static void main(String args[]){
A a1 = new B("Hello ");
A a2 = new B("World!!!");
System.out.println(a1.fun(a2));
}
};
A a2 = new B("World!!!");
这句并没有指定T的类型,所以T的实例默认为<? extends Object>类型,也就是说fun()方法可以传递任意一个Object类型的实参,那么System.out.println(a1.fun(a2));
这句其实是fun()方法通过泛型将a2自动转换成了B类型。
A a2 = new B();
这句其实是将B的实例上溯造型成了A,所以a2是A类型的。[/quote]
嗯,我知道,这个是作为辅助说明,关键是为什么顶楼的代码中不用将a2强制转型。A a2 = new B();
这句其实是将B的实例上溯造型成了A,所以a2是A类型的。
interface A<T>
{
public String fun(T t);
};
class B implements A<B>
{
private String info;
public B(String info){
this.info = info;
}
public String fun(B b){
return this.info + b.info;
}
};
public class HelloWorld
{
@SuppressWarnings("unchecked")
public static void main(String args[]){
A a1 = new B("Hello ");
A a2 = new B("World!!!");
System.out.println(a1.fun(a2));
System.out.println(a1 instanceof A);
System.out.println(a1 instanceof B);
System.out.println(a2 instanceof A);
System.out.println(a2 instanceof B);
System.out.println(a2==a1);
}
};
输出:
Hello World!!!
true
true
true
true
false
为什么要转型?
就跟:
Object str1 = new String();
Object str2 = new String();
一样,为啥要转型?
可能没增加泛型,那就换个:
List list1 = new ArrayList();
List list2 = new ArrayList();
道理一样。package test2;
interface A
{
public String fun(Object t);
};
class B implements A
{
private String info;
public B(String info){
this.info = info;
}
public String fun(Object b){
return this.info + ((B)b).info;
}
};
public class Demo
{
@SuppressWarnings("unchecked")
public static void main(String args[]){
A a1 = new B("Hello ");
A a2 = new B("World!!!");
System.out.println(a1.fun(a2));
}
};