我在創建對象時遇到了一些困惑,我在java文檔和其他編程書籍中看到了這些對象。對於例如面向對象的設計:哪個更好?
假設有一個base class
和derived class
1-我有Base
類型的變量,其是指類型的對象Derived
List<String> list = new ArrayList<String>();
2-我有Derived
類型的變量,其指的是Derived
的對象
ArrayList<String> arrList = new ArrayList<String>();
我的問題是在1和2之間進行選擇時應該如何思考?它是否利用了Polymorphism
一般的基礎派生場景?
有沒有better practice
,而選擇1和2,我不知道或只是一個personal decision
?
編輯:
對不起,列表是一個接口。 另一個問題:如果我使用Type參數,我的決定會改變嗎?
ArrayList<T> list = new ArrayList<T>();
更新答:這實際上被稱爲"Programming to the interface"
。感謝Code-Guru。正是我一直在尋找簡單來說在回答這個問題的一個解釋 - What does it mean to "program to an interface"?
選項1通常是首選(忽略抽象基類和接口之間的區別)。在OOP中,我們稱之爲「編程接口」。 – 2013-02-17 23:48:45
對不起。請看另一個問題,編輯。 – Prince 2013-02-18 00:08:46
我仍然建議你將'list'聲明爲'List'而不是'ArrayList '。更改爲類型參數不會顯着改變您的原始問題。 –
2013-02-18 00:47:04