- 一对一 person car
- 一对多 person children (自身关联)
先写基本 关系后加
package com.msc.example;
class Car{
private String cname ;
private double price ;
private Person person;
public Car() {} ;
public Car(String cname,double price){
this.cname = cname ;
this.price = price ;
}
public void setPerson(Person person){
this.person = person ;
}
public Person getPerson(){
return this.person ;
}
public void setCname(String cname){
this.cname = cname ;
}
public void setPrice(double price){
this.price = price ;
}
public String getCname(){
return this.cname ;
}
public double getPrice(){
return this.price ;
}
public String getInfo(){
return "【汽车信息】名字 = "+this.cname+" 价格 = "+ this.price ;
}
}
class Person{
private String pname ;
private int age ;
private Car car ;
private Person children[] ;
public Person() {};
public Person(String pname,int age) {
this.pname = pname ;
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 void setPname(String pname) {
this.pname = pname;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
public String getPname() {
return this.pname;
}
public String getInfo(){
return "【个人信息】 姓名 = "+this.pname+" 年龄 = "+this.age ;
}
}
public class JavaBegin {
public static void main(String args[]){
// 第一步声明对象并设置彼此的关系
Person father = new Person("张三",45) ;
Person mother = new Person("王五",46) ;
Person son = new Person("小刘",45) ;
Person daugher = new Person("小莉",45) ;
Car carA = new Car("法拉利",100000) ;
Car carB = new Car("兰博基尼",600000) ;
Car carC = new Car("奥迪",15640) ;
Car carD = new Car("奔驰",200) ;
father.setCar(carA);
carA.setPerson(father);
mother.setCar(carB);
carB.setPerson(mother);
son.setCar(carC);
carA.setPerson(son);
daugher.setCar(carD);
carD.setPerson(daugher);
father.setChildren(new Person[]{son,daugher}) ;
mother.setChildren(new Person[]{son,daugher}) ;
// 第二步根据关系获取数据
System.out.println(father.getInfo()+" and "+father.getCar().getInfo()); //人找车
System.out.println(carB.getInfo()+" and "+carB.getPerson().getInfo()); //车找人
for(Person temp : father.getChildren()){
System.out.println(temp.getInfo());
}
for(int x = 0 ;x<mother.getChildren().length;x++){
System.out.println(mother.getChildren()[x].getInfo());
}
}
}
输出: