两个对象之间的一对一关系
单向关联 单向一对一
双向关联 双向一对一 作用:可以通过任意一方得到另一方的信息
例如:
一个丈夫(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; } }
原文地址:http://12170190.blog.51cto.com/12160190/1869227