自身关联
class Car{
private float value;
private String name;
private Person person;
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setValue(float value){
this.value = value;
}
public float getValue(){
return this.value;
}
public void setPerson(Person person){
this.person = person;
}
public Person getPerson(){
return this.person;
}
public String getInfo(){
return "name"+name+"value"+value;
}
public Car(String name,float value){
this.name = name;
this.value = value;
}
}
class Person{
private String name;
private int age;
private Car car;
private Person children[];//一个人可以有很多孩子 这些孩子都是人 都有相同的类结构 不可能重复建多个类
public void setChildren(Person children[]){//注意 我第一次想的不对
this.children = children;
}
public Person[] getChildren(){//注意 我第一次想的不对
return this.children;
}
public void setName(String name){
this.name= name;
}
public String getName(){
return this.name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
public void setCar(Car car){
this.car = car;
}
public Car getCar(){
return this.car;
}
public String getInfo(){
return "name"+name+"age"+age;
}
public Person(String name,int age){
this.name = name;
this.age = age;
}
}
public class name {
public static void main(String args[]){
Person person = new Person("张三",18);
Car car = new Car("宾利", 20000000.00f);
Person childA = new Person("李四", 1);
Person childB = new Person("王五", 2);
childA.setCar(new Car("BWM X1", 300000.00f));//匿名函数
childB.setCar(new Car("法拉利", 200000.00f));//匿名函数
person.setChildren(new Person[]{childA,childB});//这里我没想到这样写
person.setCar(car);
car.setPerson(person);
System.out.println(person.getCar().getInfo());//代码链
System.out.println(car.getPerson().getInfo());//代码链
for (int i = 0; i < person.getChildren().length; i++) {
System.out.println(person.getChildren()[i].getInfo());
System.out.println(person.getChildren()[i].getCar().getInfo());
}
}
}
这些关系的匹配都是通过引用数据类型的关联来完成的
对象数组能表示多 这个概念 在实际开发中异常重要