在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 +"\r\n" ; for(int i=0;i<emps.length;i++) ret += "雇員:"+ emps[i].getEmpName() + " 編號:"+ emps[i].getEmpNo() +" 薪水:"+ emps[i].getEmpSalry() +"\r\n"; 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-鏈表實例