今天我们来学习一下类关联结构:

首先我们先写两个类 一个是Person类,一个Car类

 

类关联结构详解

 

 

现在我们来讲解一下这两个类的关系

首先一个人可以有一辆车, 现在假设这个车出车祸了我们能从这个车找到这个人,所以我们现在就引出了关联这个概念:

具体代码:

 

类关联结构详解

 

反之我们也能根据人来查找车的信息,现在我们在加深一步类的复杂程度,

现在我们这个张三有两个儿子,张三给两个儿子配了新的车,这样我们可能会说我们在写一个类,但假设这家人的孙子曾孙子我们也不能一直创建新的类,所以我们就需要继续改写这个类:

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 String getInfo(){
        return "name :" + this.name + "、price :" + this.price;
    }
    public Person getPerson(){
        return this.person;
    }
}
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 void setCar(Car car){
        this.car = car;
    }
    public String getInfo(){
        return "name" + this.name + "age" + this.age;
    }
    public Car getCar(){
        return this.car;
    }
    public Person[] getChildren(){
        return this.children;
    }
}
public class UnionClass {
    public static void main(String[] args) {
        Person person = new Person("张三",25);
        Person children1 = new Person("李四",20);
        Person children2 = new Person("王五",18);
        Car car = new Car("gtr", 2555555.00);
        children1.setCar(new Car("bwm",5555.00));
        children2.setCar(new Car("act",200000.00));
        person.setChildren(new Person[]{children2,children1});

        for(int i = 0; i < person.getChildren().length; i++){
            System.out.println(person.getChildren()[i].getInfo());
        }
    }
}

 

这里主要思路是运用了数组操作,难点可能是

类关联结构详解

因为我们在前面定义一个getChildren的方法,返回值是数组,所以我们的操作其实就是children.length.

 

 

 

相关文章:

  • 2021-12-13
  • 2022-12-23
  • 2021-08-24
  • 2021-04-28
  • 2021-08-10
  • 2021-07-05
  • 2023-01-24
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-13
  • 2021-10-14
  • 2021-12-10
  • 2021-09-03
相关资源
相似解决方案