类关联结构
class Car {
private String name;
private double price;
private Person person; // 车应该属于一个人
public Car(String name, double price) {
this.name = name;
this.price = price;
}
public String getInfo() {
return "品牌:" + this.name + "\n价格:" + this.price;
}
public void setPerson(Person person){
this.person = person;
}
public Person getPerson(){
return this.person;
}
}
class Person {
private String name;
private int age;
private Car car; // 代表一个人有一辆车
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getInfo() {
return "姓名:" + this.name + "\n年龄:" + this.age;
}
public void setCar(Car car){
this.car = car;
}
public Car getCar(){
return this.car;
}
}
public class JavaDemo {
public static void main(String[] args) {
// 申明对象并且设置彼此的关系
Person person = new Person("YTW",21);
Car car = new Car("保时捷",2000000.00);
person.setCar(car); // 一个人有一辆车
car.setPerson(person); // 一两车属于一个人
System.out.println(person.getCar().getInfo()); // 通过人找到车
System.out.println(car.getPerson().getInfo()); // 通过车找到人
}
}
// 运行结果
品牌:保时捷
价格:2000000.0
姓名:YTW
年龄:21
自身关联
package com.itheima;
class Car {
private String name;
private double price;
private Person person; // 车应该属于一个人
public Car(String name, double price) {
this.name = name;
this.price = price;
}
public String getInfo() {
return "品牌:" + this.name + "\n价格:" + this.price;
}
public void setPerson(Person person){
this.person = person;
}
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 String getInfo() {
return "姓名:" + this.name + "\n年龄:" + this.age;
}
public void setCar(Car car){
this.car = car;
}
public Car getCar(){
return this.car;
}
public void setChildren(Person[] children){
this.children = children;
}
public Person[] getChildren(){
return this.children;
}
}
public class JavaDemo {
public static void main(String[] args) {
// 申明对象并且设置彼此的关系
Person person = new Person("YTW",21);
Person child1 = new Person("ZC",1);
Person child2 = new Person("XQS",2);
child1.setCar(new Car("奥迪",200000.00));
child2.setCar(new Car("宝马",250000.00));
person.setChildren(new Person[] {child1,child2});
Car car = new Car("保时捷",2000000.00);
person.setCar(car); // 一个人有一辆车
car.setPerson(person); // 一两车属于一个人
System.out.println(person.getCar().getInfo()); // 通过人找到车
System.out.println(car.getPerson().getInfo()); // 通过车找到人
// 根据人找到所有的孩子以及孩子所拥有的车
System.out.println();
for (Person per:person.getChildren()) {
System.out.println(per.getInfo());
System.out.println(per.getCar().getInfo());
}
}
}
// 运行结果
品牌:保时捷
价格:2000000.0
姓名:YTW
年龄:21
姓名:ZC
年龄:1
品牌:奥迪
价格:200000.0
姓名:XQS
年龄:2
品牌:宝马
价格:250000.0
合成设计模式
拆分!组合!