I'm currently stuck on a project. Here's what I should do:
Copy the Employee.java file from the java1_Lesson14 project to the java1_Project14 project. First, use what you've learned about encapsulation to protect your data.
Use a call to the System.out.println() method to display in the console the names and values of all of the instance variables in each instance of the Employee class. Also print to the console the value of any static variables.
Note that, if you access a static variable via an instance, Eclipse will warn you that this is not optimal behavior. Use the correct form for accessing and displaying any static information.
I think I did the encapsulation part right. The problem now is the warnings messages I'm getting from Eclipse.
On e2.setTopSalary(199000)
I get the following message: "The static method setTopSalary(int) from the type Employee should be accessed in a static way."
And on System.out.println("e2 Top Salary is " + e2.topSalary)
: "The static field Employee.topSalary should be accessed in a static way."
Can anyone give me a light on how do I fix this?
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);
}
}
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:
and access fields by:
Employee
is the class name.