首页 > 代码库 > Java程序设计基础 面向对象 练习 静态工厂方法

Java程序设计基础 面向对象 练习 静态工厂方法

  定义静态域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程序设计基础 面向对象 练习 静态工厂方法