public class StaticTest
{
   public static void main(String[] args)
   {
      // fill the staff array with three Employee objects
      Employee[] staff = new Employee[3];      staff[0] = new Employee("Tom", 40000);
      staff[1] = new Employee("Dick", 60000);
      staff[2] = new Employee("Harry", 65000);      // print out information about all Employee objects
      for (int i = 0; i < staff.length; i++)
      {
         Employee e = staff[i];
         e.setId();
         System.out.println("name=" + e.getName()
            + ",id=" + e.getId()
            + ",salary=" + e.getSalary());
      }      int n = Employee.getNextId(); // calls static method
      //Employee v=new Employee();
      //int n = Employee.getNextId();
      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 main(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;
}
----------------------------------------------------------------
我要访问:
public static int getNextId()
   {
      return nextId; // returns static field
   } 现在getNextId()是static型 如果不是static,怎么访问?
public int getNextId()
   {
      return nextId; // returns static field
   } 书上说用一个对象引用来访问,请问如何操作?

解决方案 »

  1.   

    是static的就
    Employee.getNextId();不是的就
    Employee emp = new Employee();
    emp.getNextId();
      

  2.   

    如果是static类型:Employee.getNextId();
    如果不是:employee.getNextId();
              employee是Employee的一个实例
      

  3.   

    类的引用
    this -->
    class a = new class(args)// a is a reference
      

  4.   

    类的引用就是这个类的对象的句柄,也就是说由这个句柄来代替这个对象
    就象我们的名字,每个名字对应一个人
    类的对象放到了内存的堆里,
    而引用放到了内存的栈里,并指向相应的对象.
    而有static修饰的对象,享有固定的内存空间,
    并且多个引用指向同一个对象