现在已经确定好了人与车的关系,但是现在也可以进一步该操作的完善,例如:一个人肯定会有孩子,孩子也会成年,孩子成年之后也可以有车。
class Car{
private String name;
private int price;
private Person person; //车应该属于一个人
public Car(String name,int price){
this.name = name;
this.price = price;
}
public void setPerson(Person person){
this.person = person;
}
public Person getPerson(){
return this.person;
}
public String getInfo(){
return "汽车品牌型号:" + this.name + "、汽车价值:" + this.price;
}
}
class Person {
private String name;
private int age;
private Car car; //一个人有一辆车
private Person children[]; // 一个人有多个孩子
public Person(String name,int age){
this.name = name;
this.age = age;
}
public void setChildren(Person children[])
{
this.children = children;
}
public Person[] getChildren(){
return this.children;
}
public void setCar(Car car){
this.car = car;
}
public Car getCar(){
return this.car;
}
public String getInfo(){
return "姓名:" + this.name + "、年龄:" + this.age;
}
}
public class ArrayDemo {
public static void main(String args[]){
//第一步,声明对象并且设置彼此的关系
Person person = new Person("张三",29);
Person childA = new Person("李四",18);
Person childB = new Person("王五",19);
childA.setCar(new Car("BMW X1",300000)); //匿名对象
childB.setCar(new Car("法拉利",1500000)); //匿名对象
person.setChildren(new Person[]{childA,childB}); //一个人有多个孩子
Car car = new Car("宾利",8000000);
person.setCar(car);
car.setPerson(person);
//第二步:根据关系获取数据
System.out.println(person.getCar().getInfo()); //代码链
System.out.println(car.getPerson().getInfo());
//根据人找到所有的孩子以及孩子对应的汽车
for(int x = 0; x < person.getChildren().length; x++){
System.out.println("\t|-" + person.getChildren()[x].getInfo());
System.out.println("\t\t|-" + person.getChildren()[x].getCar().getInfo());
}
}
}
这些关系的匹配都是通过引用数据类型的关联来完成的。