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机对象。
再比如张三和李四都是人,但他们的名字不一样,可以以此区分这两个具体的人。名字应该作为人的成员变量。如果将名字叫“张三”的人和名字叫“李四”的人分别定义成两个类,均继承“人”这个类,显然是不合理的。
以上内容摘自<<Java 2认证考试指南与试题解析>>
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. } }