5.JAVA-内部类实例

在JAVA中,类内部可以添加其它类,当然也可以实现类继承(后续章节学习).

本章示例-实现部门类和雇员类

  • 可以通过部门对象,查找该部门的雇员信息.
  • 可以通过雇员对象,查找该雇员所在的部门信息

代码如下:

/*
* 部门类
*/
class Department
{
  private int DepNo;    //部门编号
  private String DepName;    //部门名称
  private String DepLoc;    //部门位置
  private Employee[] emps;    //部门的人数

  public Department(int DepNo,String DepName,String DepLoc)
  {
    this.DepNo = DepNo;
    this.DepName = DepName;
    this.DepLoc    = DepLoc;    
  }

  public void setEmps(Employee[] emps)
  {
    this.emps = emps;    
  }
  public Employee[] getEmps()
  {
    return this.emps;    
  }
  public String getDepName()
  {
    return this.DepName;    
  }
  public String getInfo()
  {
    String ret = "部门编号:"+ DepNo + " 名称:"+ DepName + " 位置:"+ DepLoc + " 部门人数:"+ emps.length +"
" ;

    for(int i=0;i<emps.length;i++)
      ret += "雇员:"+ emps[i].getEmpName() + " 编号:"+ emps[i].getEmpNo() +" 薪水:"+ emps[i].getEmpSalry() +"
";
    return ret;
  }

}

/*
* 雇员类
*/
class Employee
{
  private int EmpNo;    //雇员编号
  private String EmpName;    //雇员名称
  private int EmpSalry;    //雇员薪水
  private Department dep;    //雇员所在的部门

  public Employee(int EmpNo,String EmpName,int EmpSalry,Department dep)
  {
    this.EmpNo = EmpNo;
    this.EmpName = EmpName;    
    this.EmpSalry = EmpSalry;
    this.dep = dep;    

  } 

  public int getEmpNo()
  {
    return this.EmpNo;
  }
  public String getEmpName()
  {
    return this.EmpName ;
  }
  public int getEmpSalry()
  {
    return this.EmpSalry ;
  }

  public Department getDep()
  {
    return this.dep ;
  }

  public String getInfo()
  {
    return "雇员编号:"+ EmpNo + " 名称:"+ EmpName + " 所属部门:"+ dep.getDepName() + " 薪水:"+ EmpSalry;
  }
}


public class Test{
  public static void main(String args[]){

    //先有部门,再有雇员,所以Department构造方法里,是没有雇员的
    Department dep = new Department(7,"销售部","成都"); 
    //先有部门,再有雇员,所以Employee构造方法里,是有部门信息的
    Employee emp1 = new Employee(7760,"小张",2700,dep);
    Employee emp2 = new Employee(7761,"小李",3300,dep);
    Employee emp3 = new Employee(7762,"小王",4200,dep);

    dep.setEmps(new Employee[]{emp1,emp2,emp3});    
    System.out.println( dep.getInfo() );
  }    
}

运行打印:

下章学习:6.JAVA-链表实例

原文地址:https://www.cnblogs.com/lifexy/p/10789804.html