【发布时间】:2013-12-04 13:32:07
【问题描述】:
我有一项基本任务要做,但我对 OOP 非常陌生,并且正在为此苦苦挣扎。其他在线资源开始增加我的困惑。
我必须:
为 Person 类编写代码。 Person 对象具有名称、年龄和地址属性。
为 Dog 类编写代码。 Dog 对象将具有属性名称和年龄。
在 Person 和 Dog 类中提供在 Person 对象和 Dog 对象之间建立双向关联所需的任何附加代码。 Person 对象充当 Dog 对象的所有者,而 Dog 对象充当 Person 对象的宠物。
修改您的 Person 类,以便一个 Person 对象可以充当最多 20 个 Dog 对象的所有者。
显然这是一个非常简单的例子。
到目前为止我的代码:
人物类:
public class Person
{
// instance variables - replace the example below with your own
private String name;
private int age;
private String address;
/**
* Constructor for objects of class Person
*/
public Person()
{
this.name = name;
this.age = age;
this.address = address;
}
//Set Methods:
public void setName () {
this.name = name;
}
public void setAge () {
this.age = age;
}
public void setAddress () {
this.address = address;
}
//Get Methods:
public String getName () {
return name;
}
public int getAge () {
return age;
}
public String getAddress () {
return address;
}
}
狗类:
public class Dog
{
// instance variables - replace the example below with your own
private String name;
private int age;
public Dog()
{
this.name = name;
this.age = age;
}
//Set Methods:
public void setName () {
this.name = name;
}
public void setAge () {
this.age = age;
}
//Get Methods:
public String getName () {
return name;
}
public int getAge () {
return age;
}
}
主要:
public class Main
{
//Blank
}
我知道这段代码目前没有用,也没有做任何事情,但我不确定如何“关联”对象以及在哪里做。分配规范指定一个人充当狗的“所有者”。
这就是我的问题所在。设置对象之间的关系。
【问题讨论】:
-
您希望关系是内部的(比如一个人有一组 Dogs 作为字段,而狗有一个所有者作为字段)还是外部的(例如包含关系的地图)
-
我认为内部规范指定我必须这样做
-
"修改 Person 类,使 Person 对象可以作为最多 20 个 Dog 对象的所有者。"
-
只需在 Person 中添加 setDog(Dog pet) 方法,然后在 Dog 中添加 setOwner(Person owner) 方法。就这么简单:)
-
好莱坞原则 ;)