標籤:運行 str err 資訊 next 測試 靜態Factory 方法 rgs 定義
定義靜態域nextId和一個靜態方法getNextId,將三個Employee對象寫入數組,然後列印僱員資訊。最後列印出寫一個可用的員工標識碼來展示靜態方法。
package company;public class Gettext { public static void main(String[] args) { // TODO 自動產生的方法存根 Employee[] staff = new Employee[3]; staff[0] = new Employee("Tom",40000); staff[1] = new Employee("Dick",60000); staff[2] = new Employee("Harry",65000); for(Employee e:staff) { e.setId(); System.out.println("name= " + e.getName() + " id= " + e.getId() + " salary=" + e.getSalary()); } int n = Employee.getNextId(); System.out.println("Next available id = " + n); }}
package company;public class Employee { private static int nextId = 1; private String name; private double salary; private int id; public Employee(String name,double salary) { this.name = name; this.salary = salary; id = 0; } public String getName() { return name; } public double getSalary() { return salary; } public int getId() { return id; } public void setId() { id = nextId; nextId++; } public static int getNextId() { return nextId; } public static void main(String[] args) { //用於獨立測試Employee類 // TODO 自動產生的方法存根 Employee e = new Employee("Herry",50000); System.out.println(e.getName() + " " + e.getSalary()); }}
程式運行結果:
name= Tom id= 1 salary=40000.0
name= Dick id= 2 salary=60000.0
name= Harry id= 3 salary=65000.0
Next available id = 4
Java程式設計基礎 物件導向 練習 靜態Factory 方法