1 回答
TA贡献1887条经验 获得超5个赞
我们以一道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认证考试指南与试题解析>>
添加回答
举报