java进入编程界面_java – 编程到界面是什么意思?

你可能正在寻找这样的东西:

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;

}

还有另一个好处,在这个(至少对我来说)差异有助于我更好地设计一个程序。但希望我的例子给你一些想法…希望它有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值