类关联结构
相互独立的两个类,将它们关联起来。
例如:将Car和Person两个类关联起来。
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 person;
}
public String getInfo() {
return "汽车品牌型号:" + this.name + "、汽车价值:" + this.price;
}
}
class Person {
private String name;
private int age;
private Car car;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public String getInfo() {
return "姓名:" + this.name + "、年龄:" + this.age;
}
}
public class ArrayDemo {
public static void main(String[] args) {
//第一步:声明对象并且设置彼此的关系
Person person=new Person("林强",29);
Car car=new Car("宾利",8000000000.00);
person.setCar(car); //一个人有一辆车
car.setPerson(person); //一辆车属于一个人
//第二部:根据关系获取数据
System.out.println(person.getCar().getInfo());
System.out.println(car.getPerson().getInfo());
}
}
自身关联
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 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[] getChildren() {
return children;
}
public void setChildren(Person[] children) {
this.children = children;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = 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("BWM", 120000.00)); //匿名对象
childB.setCar(new Car("法拉利", 12000000.00)); //匿名对象
person.setChildren(new Person[]{childA, childB});
Car car = new Car("宾利", 8000000000.00);
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("\t|-" + person.getChildren()[i].getInfo());
System.out.println("\t\t|-" + person.getChildren()[i].getCar().getInfo());
}
}
}
这些关系的匹配都是通过引用数据类型的关联来完成的。