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

类的关联,不同类属性的调用

时间:2017-09-22 01:05:28      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:style   getname   ring   set   temp   name   this   rgs   class   

下面有三个类,第一个Dept(部门),存放了两个属性,部门名称和所在地址

public class Dept {
    private String name;
    private String loc;
    private Emp[] emps;
    public Dept(){
        
    }
    public Dept(String name,String loc){
        this.name=name;
        this.loc=loc;
    }
    public void setName(String name){
        this.name=name;
    }
    public String getName(){
        return this.name;
    }
    public void setLoc(String loc){
        this.loc=loc;
    }
    public String getLoc(){
        return this.loc;
    }
    public void setEmps(Emp[] emps){
        this.emps=emps;
    }
    public Emp[] getEmps(){
        return this.emps;
    }
    public String getInfo(){
        return "部门名称:"+this.name+",部门地址:"+loc;
    }
}

第二个类Emp(雇员)存放了两个属性,雇员的姓名和年龄

public class Emp {
    private String name;
    private int age;
    private Dept dept;
    public Emp(){
        
    }
    public Emp(String name,int age){
        this.name=name;
        this.age=age;
    }
    public void setName(String name){
        this.name=name;
    }
    public String getName(){
        return this.name;
    }
    public void setAge(int age){
        this.age=age;
    }
    public int getAge(){
        return this.age;
    }
    public void setDept(Dept dept){
        this.dept=dept;
    }
    public Dept getDept(){
        return this.dept;
    }
    public String getInfo(){
        return "我的名字叫:"+this.name+",我今年"+this.age+"了";
    }
}

第三个类,主类,初始化类的属性,关联两个类,并调用类的属性

public class App {
    public static void main(String[] args) {
        Dept dt1=new Dept("财务部","洛杉矶");
        Dept dt2=new Dept("行政部","纽约");
        Dept dt3=new Dept("环保部","德克萨斯州");
        
        Emp em1=new Emp("大卫",24);
        Emp em2=new Emp("科比",25);
        Emp em3=new Emp("弗兰克林",26);
        Emp em4=new Emp("伯德",27);
        Emp em5=new Emp("拉里",28);
        Emp em6=new Emp("布什",29);
        
        em1.setDept(dt1);
        System.out.println(em1.getInfo());
        System.out.println("\t"+em1.getDept().getInfo());
        
        dt2.setEmps(new Emp[]{em4,em5,em6});
        for(int i=0;i<dt2.getEmps().length;i++){
            System.out.println(dt2.getEmps()[i].getInfo());
        }
    }
}

此处输出:

技术分享

类的关联,不同类属性的调用

标签:style   getname   ring   set   temp   name   this   rgs   class   

原文地址:http://www.cnblogs.com/FrankLiner/p/7572111.html

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