java 类关联 自身关联PLUS

class Person{
private String name;
private int age;
private Car car;
private Person children [] ; 在人类跟车类 之后 建立CHildren属性自身关联 将孩子加入人类
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 car;
}
public Person(String name,int age){
this.name=name;
this.age=age;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age=age;
}
public int getAge(){
return age;
}
public String getInfo(){
return “人名:”+name+" 年龄:"+age;
}
}
class Car{
private String name;
private int price;
private Person person;
public void setPerson(Person person){
this.person=person;
}
public Person getPerson(){
return person;
}
public Car(String name,int price){
this.name=name;
this.price=price;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setPrice(int price){
this.price=price;
}
public int getPrice(){
return price;
}
public String getInfo(){
return “车名:”+name+" 价格:"+price;
}
}

public class javaclassplus {
public static void main(String[] args){
    Person p1 =new Person("张三",18);
    Person c1=new Person("李四",15);  创建人c1  
    Person c2=new Person("王五",16);
    p1.setChildren(new Person [] {c1,c2});    将c1 添加进Person 中的孩子属性
    Car a1=new Car("bwm",2000);
    Car a2=new Car("dazhong ",564151651);  建立新的车实例  a2 
    p1.setCar(a1);
    a1.setPerson(p1);
    c1.setCar(a2);   将孩子 c1  与 a2 车辆相关联
    a2.setPerson(c1);
    System.out.println(p1.getCar().getInfo());
    System.out.println(a1.getPerson().getInfo());
    System.out.println(c1.getCar().getInfo());
    System.out.println(a2.getPerson().getInfo());
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值