0

我目前被困在一个项目上。这是我应该做的:

  1. 将 Employee.java 文件从 java1_Lesson14 项目复制到 java1_Project14 项目。首先,使用您所学到的有关封装的知识来保护您的数据。

  2. 使用对 System.out.println() 方法的调用在控制台中显示 Employee 类的每个实例中所有实例变量的名称和值。还将任何静态变量的值打印到控制台。

  3. 请注意,如果您通过实例访问静态变量,Eclipse 会警告您这不是最佳行为。使用正确的表格来访问和显示任何静态信息。

我认为我做对了封装部分。现在的问题是我从 Eclipse 收到的警告消息。

e2.setTopSalary(199000)我收到以下消息:“应以静态方式访问来自 Employee 类型的静态方法 setTopSalary(int)。”

然后System.out.println("e2 Top Salary is " + e2.topSalary):“应以静态方式访问静态字段 Employee.topSalary。”

谁能告诉我如何解决这个问题?

public class Employee {
    private static int topSalary = 195000;
    private int hoursPerWeek;
    public static void setTopSalary (int s) { 
        if (s > topSalary)
            topSalary = s;
    }

    public void addMoreHours() {
        hoursPerWeek++;
    }

    public static void main(String[] args) {
        Employee e1, e2;
        e1 = new Employee();
        e2 = new Employee();
        Employee.setTopSalary(199000);
        e2.setTopSalary(199001);
        e1.hoursPerWeek = 40;
        e2.hoursPerWeek = 45;
        System.out.println("Employee Top Salary is " + Employee.topSalary);
        System.out.println("e2 Top Salary is " + e2.topSalary);
        System.out.println("e1 working hours per week are " + e1.hoursPerWeek);
        System.out.println("e2 working hours per week are " + e2.hoursPerWeek);
    }

}
4

1 回答 1

1

The static keyword means that all instances of the class still refer to one instance of the field. That field is effectively per-class.

You call it as follows:

Employee.setTopSalary(12000);

and access fields by:

System.out.println(Employee.topSalary);

Employee is the class name.

于 2013-07-11T19:08:42.643 回答