通过Employee类,认识理解静态域和静态方法,employee静态,这个程序包含了Emplo
分享于 点击 13793 次 点评:176
通过Employee类,认识理解静态域和静态方法,employee静态,这个程序包含了Emplo
这个程序包含了Employee类的一个简单版本,其中包含一个静态域nextId和一个静态方法getNextId。这里用三个Employee对象填充数组,然后打印员工信息。最后,打印出下一个可用的员工标志码来作为对静态方法使用的演示。
注意:Employee类也有一个静态的main方法用于单元测试。试试运行
java Employee
和
java StaticTest
来执行两个main方法。
package Test;public class StaticTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //fill the staff array with three Employee objects Employee[] staff = new Employee[3]; staff[0] = new Employee("Tom", 40000); staff[1] = new Employee("Chris", 60000); staff[2] = new Employee("Harry", 65000); //print out information about all Employee objects for (Employee e:staff) { e.setId(); System.out.println("name="+e.getName()+",id="+e.getId()+",salary="+e.getSalary()); } int n = Employee.getNextId();//calls static method System.out.println("Next available id="+n); }}class Employee{ public Employee(String n, double s) { name = n; salary = s; id = 0; } public String getName() { return name; } public double getSalary() { return salary; } public int getId() { return id; } public void setId() { id = nextId;//set id to next available id nextId++; } public static int getNextId() { return nextId;//returns static field } public static void man (String [] args)//unit test { Employee e = new Employee("Harry", 50000); System.out.println(e.getName()+" "+e.getSalary()); } private String name; private double salary; private int id; private static int nextId = 1; }//该片段来自于http://byrx.net
用户点评