I'm having problems getting a method from one class to work if I put the objects into a set.
So I have
public class Employee {
/* instance variables */
private String firstName;
private String employeeNumber;
public Employee(String employNum) {
super();
this.employeeNumber = employNum;
}
...
public String getFirstName() {
return this.firstName;
}
There is lots of other code which I can post if needed but I'm not allowed to change the Employee
class.
So for my code I have to create a class for a Set
of Employee
s which I've done with
public class Records {
public Set<Employee> employeeSet = new HashSet<Employee>();
public Records() {
}
}
Now I need a method that will print the details of all employees in the set. Here is my attempt so far
public void printEmployeeNames() {
for (String employee : employeeSet) {
System.out.println(this.employeeSet.getFirstName());
}
}
The problem I'm having is that it won't compile as it says
"incompatible types"
and highlights employeeSet
in
for (String employee : employeeSet)
My other problem is that it can't access the method for getFirstName()
. I've tried to isolate the method using
public void printEmployeeNames() {
System.out.println(this.employeeSet.getFirstName());
}
This also won't compile as it states
"cannot find symbol - method getFirstName()".
Edit. Thanks for the help with this problem, I changed it to this and it worked.
public void printEmployees()
{
for (Employee employee: employeeSet)
{
System.out.println(employee.getFirstName());
}
}
In Java, a method can be invoked from another class based on its access modifier. For example, a method created with a public modifier can be called from inside as well as outside of a class/package. The protected method can be invoked from another class using inheritance.
It is an instance of a class. In this article, Implement the same method in Multiple Classes The implementation of the same method in multiple classes can be achieved by using Interfaces.
We can call a static method by using the ClassName. methodName. The best example of the static method is the main() method. It is called without creating the object.
this here makes no sense:
for (String employee: employeeSet)
{
System.out.println(this.employeeSet.getFirstName());
}
since the employeeSet is a Set and sets dont have a method called getFirstName
for (Employee employee: employeeSet) //for every EMPLOYEE in the employeeSet
{
System.out.println(employee.getFirstName()); //from that employ get the name
}
AND create in the Employee class the respective Setter and getters
in this case:
private String firstName;
/**
* @return the employeeNumber
*/
public final String getEmployeeNumber() {
return firstName;
}
That should be
for (Employee employee: employeeSet)
{
System.out.println(employee.getFirstName());
}
Set
doesn't have a firstname method. Your employee
object have have.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With