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;
}
還有另一個好處,在這個(至少對我來說)差異有助于我更好地設計一個程序。但希望我的例子給你一些想法…希望它有所幫助。
總結
以上是生活随笔為你收集整理的java进入编程界面_java – 编程到界面是什么意思?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql特效_MySQL树 – 前
- 下一篇: 我的世界java手机版下载1.15_我的