类的关联结构
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; //自定义属性,一个人有一辆车
public People(){}
public People(String name,int age){
this.name=name;
this.age=age;
}
//获取车辆信息
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);
Car car=new Car("宝马",400000.0);
people.setCar(car);//人—车数据传输
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());
}
}
/*
汽车型号:宝马、价格400000.0
汽车型号:宝马、价格400000.0
车主:凌强、年龄:24
车主:凌强、年龄:24
*/
本次操作的两个类型:People、Car都是自定义类型,但是都可以明确描述准确的描述出某一类群体,现在是针对某一类群体做出的一种设置,也可看做:类的基础引用过程。