分别在两个类中定义对方的类类型变量 双向 如果只关联一方,就是单向
public class NinetyFour { public static void main(String[] args) { Husband h = new Husband("小白",‘男‘); Wife w = new Wife("星星",20); //关联对象 h.setWife(w); w.setHusband(h); //通过丈夫取妻子的东西 System.out.println("我是:"+h.getName()+",我的妻子是:"+h.getWife().getName()+",她今年"+h.getWife().getAge()+"岁了"); } } //丈夫类 class Husband{ private String name; private char sex; private Wife wife;//关联妻子类 public Husband(){} public Husband(String name, char sex) { super(); this.name = name; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } public Wife getWife() { return wife; } public void setWife(Wife wife) { this.wife = wife; } } //妻子类 class Wife{ private String name; private int age; private Husband husband;//关联丈夫类 public Wife(){} public Wife(String name, int age) { super(); this.name = name; this.age = age; } 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 Husband getHusband() { return husband; } public void setHusband(Husband husband) { this.husband = husband; } }
时间: 2024-10-18 23:37:48