package asrfasf;
class Car{
private String name;
private double price;
private People people; //车属于一个人
public Car(){}
public Car(String name,double price){
this.name=name;
this.price=price;
}
public void setPeople(People people){
this.people=people;
}
public People getPeople(){
return this.people;
}
//set,get 略
public String getInfo(){
return "汽车型号:"+this.name+"、价格"+this.price;
}
}
class People{
private String name;
private int age;
private Car car; //自定义属性,一个人有一辆车
private People children []; // 自身关联操作,people找child
public People(){}
public People(String name,int age){
this.name=name;
this.age=age;
}
public void setChildren(People children[]){
this.children=children;
}
public People [] getChildren(){
return this.children;
}
//获取车辆信息
public void setCar(Car car){
this.car=car;
}
public Car getCar(){
return this.car;
}
//set get 略
public String getInfo(){
return "车主:"+this.name+"、年龄:"+this.age;
}
}
public class Demo2 {
public static void main(String[] args) {
// 声明,创建实体对象并设置彼此关系
People people=new People("凌强",24);
People child1=new People("阿伟",12);
People child2=new People("盼盼",11);
Car car=new Car("宝马",400000.0);
people.setCar(car);//人—车数据获取
child1.setCar(new Car("法拉利",20000000.00)); //匿名对象
child2.setCar(new Car("bmw",300000.0)); //匿名对象
people.setChildren(new People[]{child1,child2});
car.setPeople(people);//车—人数据获取
//根据关系获取数据
/*System.out.println(people.getCar().getInfo());//代码链。等同于car.getInfo()
System.out.println(car.getInfo());
System.out.println(car.getPeople().getInfo());//等同于people.getInfo()
*/
System.out.println(people.getInfo());
//根据人找到所有的孩子以及孩子对应的车
for(int x=0;x<people.getChildren().length;x++){
System.out.println("\t-"+people.getChildren() [x].getInfo());//根据人获得孩子信息
System.out.println("\t\t-"+people.getChildren()[x].getCar().getInfo());//根据大人获得孩子的全部信息
}
}
}
/*
车主:凌强、年龄:24
-车主:阿伟、年龄:12
-汽车型号:法拉利、价格2.0E7
-车主:盼盼、年龄:11
-汽车型号:bmw、价格300000.0
*/
java类中的自身关联(引用传递)
猜你喜欢
转载自blog.csdn.net/qq_20799821/article/details/103354227
今日推荐
周排行