声明Java的区别

时间:2017-06-23 11:03:34

标签: java duplicates declaration

我是Java新手,我只是为了好玩而编码,我对此感到疑惑。

Set<Employee> employees1 = new HashSet<Employee>();
HashSet<Employee> employees2 = new HashSet<Employee>();

这两个声明有什么不同吗?我的意思是“幕后”?我在这里寻找类似的问题,但我找不到任何可能因为我不知道如何解释搜索字段中的问题。

2 个答案:

答案 0 :(得分:2)

Set是一个接口,其中HashSet是实现该接口的类。

Set<Employee> employees1 = new HashSet<Employee>();

通过引用变量employees1,您只能调用{strong> HashSet类的那些在Set接口中声明并在HashSet中重写的方法

HashSet<Employee> employees2 = new HashSet<Employee>();

通过使用employees2,您将能够调用Set接口和HashSet类自己的方法(未在Set接口中声明)的重写方法。

答案 1 :(得分:0)

Set是一个接口,而HashSet是其实现之一。

如果您的变量声明为Set,则可以将其他实现作为值。 EG:

employees1 = new TreeSet<Employee>();