1 回答

TA貢獻(xiàn)1887條經(jīng)驗 獲得超5個贊
我們以一道scjp考題為例,來講解"is a"和"has a"的區(qū)別 :
Your chief Software designer has shown you a sketch of the new Computer parts system she is about to create. At the top of the hierarchy is a Class called Computer and under this are two child classes. One is called LinuxPC and one is called WindowsPC.
The main difference between the two is that one runs the Linux operating System and the other runs the Windows System. Under the WindowsPC are two Sub classes one called Server and one Called Workstation. How might you appraise your designers work?
a) Give the goahead for further design using the current scheme
b) Ask for a re-design of the hierarchy with changing the Operating System to a field rather than Class type
c) Ask for the option of WindowsPC to be removed as it will soon be obsolete
d) Change the hierarchy to remove the need for the superfluous Computer Class.
答案:b
解析:本題考察的知識點是“is a”和“has a”的區(qū)別?!癷s a”代表的是類之間的繼承關(guān)系,比如PC機(jī)是計算機(jī),工作站也是計算機(jī)。PC機(jī)和工作站是兩種不同類型的計算機(jī),但都繼承了計算機(jī)的共同特性。因此在用 Java語言實現(xiàn)時,應(yīng)該將PC機(jī)和工作站定義成兩種類,均繼承計算機(jī)類。
“has a”代表的是對象和它的成員的從屬關(guān)系。同一種類的對象,通過它們的屬性的不同值來區(qū)別。比如一臺PC機(jī)的操作系統(tǒng)是Windows,另一臺PC機(jī)的操作系統(tǒng)是Linux。操作系統(tǒng)是PC機(jī)的一個成員變量,根據(jù)這一成員變量的不同值,可以區(qū)分不同的PC機(jī)對象。
再比如張三和李四都是人,但他們的名字不一樣,可以以此區(qū)分這兩個具體的人。名字應(yīng)該作為人的成員變量。如果將名字叫“張三”的人和名字叫“李四”的人分別定義成兩個類,均繼承“人”這個類,顯然是不合理的。
以上內(nèi)容摘自<<Java 2認(rèn)證考試指南與試題解析>>
添加回答
舉報