Java中is-a和has-a的區別
1.“is-a”是繼承的關系,比如人是動物,人和動物是繼承的關系;
2.“has-a”是聚合的關系,比如人有眼睛,人和眼睛是聚合的關系;
也可以理解為 is-a 是“繼承”
但has-a是“接口”關系。是“相互依賴”的關系,同時它們的生命周期都是一樣的。
我們以一道scjp考題為例,來講解"is a"和"has a"的區別 :
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”的區別。“is a”代表的是類之間的繼承關系,比如PC機是計算機,工作站也是計算機。PC機和工作站是兩種不同類型的計算機,但都繼承了計算機的共同特性。因此在用?Java語言實現時,應該將PC機和工作站定義成兩種類,均繼承計算機類。
“has a”代表的是對象和它的成員的從屬關系。同一種類的對象,通過它們的屬性的不同值來區別。比如一臺PC機的操作系統是Windows,另一臺PC機的操作系統是Linux。操作系統是PC機的一個成員變量,根據這一成員變量的不同值,可以區分不同的PC機對象。
再比如張三和李四都是人,但他們的名字不一樣,可以以此區分這兩個具體的人。名字應該作為人的成員變量。如果將名字叫“張三”的人和名字叫“李四”的人分別定義成兩個類,均繼承“人”這個類,顯然是不合理的。
以上內容摘自<>
1. IS-A, HAS-A兩種經典OO模式:
1.1 You can just use IS-A to figure out the relationship of Subclass and Superclass. If B is a A, that means class B extends class A. That‘s TRUE everywhere in the inheritance tree.
Example: Canine(犬科動物) is-A Animal, So Class Canine extends Animal; Wolf is-A Canine, So class wolf extends Canine; But note you can‘t change their position, Animal is-A Canine never happen, so class animal never extends Canine.
1.2 HAS-A, we can remember a case: Bathroom HAS-A Tub, Tub NEVER HAS-A Bathroom, that means class Bathroom has a instance variable(field) of class tub.
as we can see:
public class Bathroom()
{ private Tub tub;
Tub.flush(); }
public class Tub()
{ public void flush()
{ //more flush code here. } }
原文:https://www.cnblogs.com/asasooo998/p/11622644.html