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
关系。
最佳答案
MyApp 没有 Employee,没有定义成员。 MyApp 有 main 方法,就是这样。根据下面的代码,MyApp has-a Employee
。
public class MyApp implements Mungeable {
public void doMunging() { ; }
private Employee;
public static void main(String[] args) {
Employee e = new Employee();
e.setName("bob");
System.out.print(e.getName());
}
}
关于java - 类是否必须位于同一继承树上才能具有 Has-A 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8703228/