6.12 自身关联

发布时间 2023-06-05 23:19:06作者: 盘思动
class Car {
    private String name;
    private double price;
    private Person person;// 车应该属于一个人
    public Car (String name,double price){
        this.name = name;
        this.price = price;
    }
    
    public void setPerson(Person person){
        this.person = person;
    }

    public Person getPerson(){
        return this.person;
    }

    public String getCarInfo(){
        return "汽车品牌:" + name + ",价格:" + 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 getPersonInfo(){
        return "姓名:" + this.name + ",年龄:" + this.age;
    }
    // setter,getter 略

}

public class HelloWorld {
    public static void main(String[] args){
        // 第一步.声明对象并且设置彼此的关系
        Person person = new Person("吴硕",20);
        Person childA = new Person("林强",19);
        Person childB = new Person("郭仁义",19);
        childA.setCar(new Car("bmw x1",3000000.00));
        childB.setCar(new Car("法拉第",1500000000.00));
        person.setChildren(new Person [] {childA,childB});

        Car car = new Car("宾利",100000.00);

        person.setCar(car);     // 一个人有一辆车
        car.setPerson(person);  // 一辆车属于一个人

        // 第二步:根据关系获取数据
        System.out.println(person.getCar().getCarInfo());// 从人找车
        System.out.println(car.getPerson().getPersonInfo());// 从车找人;
        
        System.out.println("------------");
        for (int x = 0; x < person.getChildren().length;x++){
            System.out.println("\t|- " + person.getChildren()[x].getPersonInfo());
            System.out.println("\t\t|-" + person.getChildren()[x].getCar().getCarInfo());
        }
    }

}

// 这些关系的匹配都是通过引用数据类型的关联来完成的。---实际开发中很常见!