demand:每個人都有一輛車或者沒有車。ide
design ideas:設計兩個類,車、人。人跟車之間經過引用傳遞實現互相引用。this
code:idea
//人、車都是獨立產生,產生以後再發生關係、即Member跟Car都是一個獨立的對象。然後經過產生對象再發生關係。spa
class Member {
//setter、getter略
private int mid;
private String name;
private Car car; //表示屬於人的車 若是car有實例化對象,表示有車,若是car爲null,則沒有車;
public Member(int mid, String name) {
this.mid = mid;
this.name = name;
}
public String getInfo() {
return "人員編號:" + this.mid + "人員名字:" + this.name;
}
public void setCar(Car car) {
this.car = car;
}
public Car getCar() {
return this.car;
}
}
class Car {
//setter、getter略
private String pname;
private Member member;//車屬於人
public Car(String pname) {
this.pname = pname;
}
public String getInfo() {
return "車的名字:" + this.pname;
}
public void setMember(Member member) {
this.member = member;
}
public Member getMember() {
return this.member;
}
}
public class Main {
public static void main(String args[]) {
Member m=new Member(1,"張三");//根據定義的結構關係設置數據;
Car c=new Car("法拉利458");//根據定義的結構關係設置數據;
m.setCar(c);
c.setMember(m);
System.out.println(c.getMember().getInfo());//根據定義的結構關係取出數據; }}