A<? extends B> p,尖括号里面表示参数是B的子类,为什么下面的程序有错?
import java.util.*;
public class Test2
{
public static void main(String[] args)
{
C b = new C("efg", 20, 'F');
C c = new C("abc", 30, 'M');
A<C> x = new A<C>(b, c);
printC(x);
}
public static void printC(A<? extends B> p) //这里为什么不用A<T> p呢?
{
C first = p.getFirst();
C second = p.getSecond();
System.out.println(first.getGender());
}
}
class A<T>
{
public A(T first, T second)
{
this.first = first;
this.second = second;
}
public void setFirst(T newValue)
{
first = newValue;
}
public T getFirst()
{
return first;
}
public void setSecond(T newValue)
{
second = newValue;
}
public T getSecond()
{
return second;
}
private T first;
private T second;
}
class B
{
public B(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
private String name;
private int age;
}
class C extends B
{
public C(String name, int age, char gender)
{
super(name, age);
gender = 'F';
}
public void setGender(char x)
{
gender = x;
}
public char getGender()
{
return gender;
}
private char gender;
}
错误提示为
但是我觉得既然<? extends B>参数是B的子类,为什么不能用
C first = p.getFirst();
C second = p.getSecond();
当然如果把C改成B
B first = p.getFirst();
B second = p.getSecond();
这个程序就对了,但是我就是不明白为什么不能用C?
------解决方案--------------------
http://tieba.baidu.com/p/2033128717