我现在正在学习Java类。
我有班主任。从Person我有两个子类,父亲和母亲。一个父亲可以有三个孩子(孩子1、孩子2、孩子3)。现在我想与孩子的父亲共同接触。我怎么能那样做?
我当前的代码:
班级人物
public class Person {
String name;
int age;
String addresse;
public Person (){
}
public Person(String name, int age, String addresse) {
this.name = name;
this.age = age;
this.addresse = addresse;
}
}
班级父亲
public class Father extends Person {
Person child1;
Person child2;
Person child3;
public Father() {
}
public Father(String name, int age, String addresse) {
this.name = name;
this.age = age;
this.addresse = addresse;
}
public void setName(Name name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
我的main。java
我创建一个父亲和一个人,并将其分配给子1。
public class PersonTest {
public static void main(String[] args) {
Father f = new Father();
f.setName("Joe");
Person p1 = new Person();
p1.setName("Kai")
f.child1 = p1;
}
}
现在,我想通过p1得到孩子1的父亲的名字。我怎么能那样做?
您可以在孩子和父亲之间创建双向依赖关系。如果这是一个好的设计决策-不是我答案的一部分。
public class Person {
String name;
int age;
String addresse;
Father father;
public Person (){
}
public Person(String name, int age, String addresse) {
this.name = name;
this.age = age;
this.addresse = addresse;
}
public void setFather(Father father) {
this.father = father;
}
}
创建一个进行双向链接的setter:
public class Father extends Person {
Person child1;
Person child2;
Person child3;
public Father() {
}
public Father(String name, int age, String addresse) {
this.name = name;
this.age = age;
this.addresse = addresse;
}
public void setName(Name name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setChild1(Person child1) {
this.child1 = child1;
this.child1.setFather(this);
}
}
这样称呼它:
public class PersonTest {
public static void main(String[] args) {
Father f = new Father();
f.setName("Joe");
Person p1 = new Person();
p1.setName("Kai")
f.setChild1(p1);
// p1.father
}
}