在进行类联描述的过程中,除了可以关联其他类之外,也可以实现自身的关联操作,现在假设一个人员会有一辆车,那么每个人员可能还有自己的子女,而子女也有可能有一辆车,这个时候就可以利用自身关联的形式描述人员后代的关系;
接下来就针对这一问题来实现代码的实现:
实现一个车的类:
public class Car { //描述汽车
private String name; //汽车名称
private double price; //汽车价格
private Person person; //车应该属于一个人
public Car(String name, double price) { //构造传入汽车信息
this.name = name;
this.price = price;
}
public Car() { //构造无参函数
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public String getInfo() { //获取汽车的信息
return "汽车品牌型号:" + this.name + "汽车的价格:" + this.price;
}
}
实现人的类:
public 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 Person() { //设置无参函数
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Car getCar() {
return car;
}
public void setCar(Car car) { //设置人与汽车的关系
this.car = car;
}
public Person[] getChildren() {
return children;
}
public void setChildren(Person[] children) { //设置人与孩子关联
this.children = children;
}
public String getInfo() { //获取人员信息
return "人的姓名:" + this.name + "人的年龄:" + this.age;
}
}
测试代码:
public class JavaDemo {
public static void main(String[] args) {
Person person = new Person("阿飞",28); //实例化person类对象
Person childA = new Person("大飞" ,35); //孩子(人)对象
Person childB = new Person("小飞" ,18); //孩子(人)对象
childA.setCar(new Car("奔驰" , 400000)); //匿名对象
childB.setCar(new Car("宝马" , 500000)); //匿名对象
person.setChildren(new Person[] {childA, childB}); //一个人有多个孩子
Car car = new Car("奔驰 G50", 158800.00); //实例化 Car类对象
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(person.getChildren()[i].getInfo());
System.out.println(person.getChildren()[i].getCar().getInfo());
}
}
}
运行的结果如下图:
在本程序中利用对象数组(private Person children[];)描述了一个人拥有孩子的信息,这样就在Person类的内部定义了一个自身引用,并且其结构与Person完全相同,于是孩子可以继续描述拥有的汽车或后代的信息关联。