日期:2014-05-20  浏览次数:20641 次

为什么这个泛型不成功?
下面这个程序编译不通过。

import java.util.*;

public class Test2
{
public static void main(String[] args)
{
Employee a = new Employee("abc", 2000);
Employee b = new Employee("efg", 6000);

A<Employee> c = new A<Employee>(a ,b);
                                    
}
}

class A
{
public A(Object first, Object second)
{
this.first = first;
this.second = second;
}

public Object getFirst()
{
return first;
}

public Object getSecond()
{
return second;
}

public void setFirst(Object newValue)
{
first = newValue;
}

public void setSecond(Object newValue)
{
second = newValue;
}
private Object first;
private Object second;
}

class Employee
{
String name;
double salary;

public Employee(String name, double salary)
{
this.name = name;
this.salary = salary;
}
}


错误提示为


------解决方案--------------------
A类改为如下

 class A<T> {

        public A(T first, T second) {
            this.first = first;
            this.second = second;
        }

        public T getFirst() {
            return first;
        }

        public T getSecond() {
            return second;
        }

        public void setFirst(T newValue) {
            first = newValue;
        }

        public void setSecond(T newValue) {
            second = newValue;
        }
        private T first;
        private T second;
    }

------解决方案--------------------
你的Class A 得带上泛型的吧

Class A<T> {
   //...
}
------解决方案--------------------
你要A类使用泛型,首先得Class A<T>{}