类是否必须位于同一继承树上才能具有 Has-A 关系
class Employee {
private String name;
void setName(String n) { name = n; }
String getName() { return name; }
}
interface Mungeable {
void doMunging();
}
public class MyApp implements Mungeable {
public void doMunging() { ; }
public static void main(String[] args) {
Employee e = new Employee();
e.setName("bob");
System.out.print(e.getName());
}
}
以及可能的答案:
Which are true? (Choose all that apply.)
A. MyApp is-a Employee.
B. MyApp is-a Mungeable.
C. MyApp has-a Employee.
D. MyApp has-a Mungeable.
E. The code is loosely coupled.
F. The Employee class is well encapsulated.
在回答上述问题时,我选择了选项 B
、C
、E
和 F
显然正确答案只有 B
、E
和 F
。为了使 MyApp 与 Employee
具有 Has-A
关系,两者必须位于同一继承树层次结构中。这是正确的吗?我认为如果一个类将对象作为成员,它会自动具有 Has-A
关系。
class Employee {
private String name;
void setName(String n) { name = n; }
String getName() { return name; }
}
interface Mungeable {
void doMunging();
}
public class MyApp implements Mungeable {
public void doMunging() { ; }
public static void main(String[] args) {
Employee e = new Employee();
e.setName("bob");
System.out.print(e.getName());
}
}
And the possible answers:
Which are true? (Choose all that apply.)
A. MyApp is-a Employee.
B. MyApp is-a Mungeable.
C. MyApp has-a Employee.
D. MyApp has-a Mungeable.
E. The code is loosely coupled.
F. The Employee class is well encapsulated.
While answering the above question i selected options B
,C
,E
and F
Apparently the only correct answers are B
,E
and F
. For MyApp to have a Has-A
relationship with Employee
both have to be in the same inheritance tree hierarchy. Is this correct? I thought that if a class has the object as a member it automatically has a Has-A
relationship.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
MyApp 没有 Employee,没有定义任何成员。 MyApp 有 main 方法,就是这样。根据下面的代码,
MyApp has-a Employee
。MyApp doesn't have Employee, no member is defined. MyApp has main method, thats it. As per below code,
MyApp has-a Employee
.这是不正确的。
你是对的。要点是,
MyApp
没有Employee
作为成员。It is not correct.
You were right. Point is,
MyApp
does not haveEmployee
as a member.为了使
MyApp
与Employee
建立关系,Employee e
应该是一个成员变量,而不仅仅是在静态方法中本地实例化。For
MyApp
to have a relationship toEmployee
,Employee e
should be a member variable and not just be instantiated locally in a static method.否, 例如:
No, e.g.:
这是不正确的。它与员工类紧密耦合,为了松散耦合,它必须在接口或抽象类上工作。为了使其松散耦合,代码如下。
It's not correct. It is tightly coupled with employee class, for it to be loosely coupled, it must either work on interface or an abstract class. To make it loosely coupled, code would be as following.