你可能正在寻找这样的东西:
public static void main(String... args) {
// do this - declare the variable to be of type Set, which is an interface
Set buddies = new HashSet();
// don't do this - you declare the variable to have a fixed type
HashSet buddies2 = new HashSet();
}
为什么以第一种方式做好考虑呢?假设稍后你决定使用一个不同的数据结构,比如说LinkedHashSet,以便利用LinkedHashSet的功能。代码必须如下更改:
public static void main(String... args) {
// do this - declare the variable to be of type Set, which is an interface
Set buddies = new LinkedHashSet(); //
// don't do this - you declare the variable to have a fixed type
// this you have to change both the variable type and the constructor call
// HashSet buddies2 = new HashSet(); // old version
LinkedHashSet buddies2 = new LinkedHashSet();
}
这看起来不是那么糟,对吧?但是如果你用相同的方式写getter呢?
public HashSet getBuddies() {
return buddies;
}
这也必须改变!
public LinkedHashSet getBuddies() {
return buddies;
}
希望你看到,即使有这样一个小程序,你对你声明变量的类型有深远的影响。随着对象来回传播,这绝对有助于使程序更容易编码和维护,如果您只是依赖于声明为接口的变量,而不是该接口的特定实现(在这种情况下,将其声明为设置,不是LinkedHashSet或其他)。可以这样:
public Set getBuddies() {
return buddies;
}
还有另一个好处,在这个(至少对我来说)差异有助于我更好地设计一个程序。但希望我的例子给你一些想法…希望它有所帮助。