對象的一對一關係

兩個對象之間的一對一關係


單向關聯  單向一對一

雙向關聯  雙向一對一 作用:可以通過任意一方得到另一方的信息


例如:

一個丈夫(husband)對一個妻子(wife)

public class OneToOne {

	public static void main(String[] args) {
		Husband h=new Husband("牛郎",'男');
		Wife w=new Wife("織女",22);
		//關聯關係
		h.setWife(w);
		w.setHusband(h);
		
		System.out.println(h.getName()+"的妻子是"+h.getWife().getName()+",她今年"+h.getWife().getAge()+"歲了。");
        //輸出:牛郎的妻子是織女,她今年22歲了。
	}

}
/**
 * 
 * 丈夫類
 *
 */
public class Husband {
	private String name;
	private char sex;
	private Wife wife;//關聯妻子類,把對方的類作爲自己的屬性來表示
	
	public Husband(String name, char sex) {
		this.name = name;
		this.sex = sex;
	}
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the sex
	 */
	public char getSex() {
		return sex;
	}
	/**
	 * @param sex the sex to set
	 */
	public void setSex(char sex) {
		this.sex = sex;
	}

	public Wife getWife() {
		return wife;
	}

	public void setWife(Wife wife) {
		this.wife = wife;
	}

}
/**
 * 
 * 妻子類
 *
 */
public class Wife {
	private String name;
	int age;
	private Husband husband;//關聯丈夫類,把對方的類作爲自己的屬性來表示
	
	public Wife(String name, int age) {
		this.name = name;
		this.age = age;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}

	/**
	 * @param age the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}
	
	public Husband getHusband() {
		return husband;
	}

	public void setHusband(Husband husband) {
		this.husband = husband;
	}
	

}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章