码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象_对象的一对一关系

时间:2015-04-05 20:08:22      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

分别在两个类中定义对方的类类型变量          双向        如果只关联一方,就是单向

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;
    }
    
}

 

面向对象_对象的一对一关系

标签:

原文地址:http://www.cnblogs.com/LO-ME/p/4394483.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!