0

I am working with Java and trying to write a very simple test code like this to test and I thought that there was no problem but there was one problem.


public class EmployeeTest {
    public static void main(String[] args){
        Employee[] staff = new Employee[1];
        staff[0] = new Employee("Carl Cracker", 75000);
        for (Employee e : staff)
            System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
    }
    
class Employee
{
    private String name;
    private double salary;
    public Employee(String n, double s)
    {
        name = n;
        salary = s;
    }
    public String getName()
    {
        return name;
    }
    public double getSalary()
    {
        return salary;
    }
}
}

Unfortunately, when I ran my code, the result is

No enclosing instance of type EmployeeTest is accessible. Must qualify the allocation with an enclosing instance of type EmployeeTest (e.g. x.new A() where x is an instance of EmployeeTest).

I am sure that my code is very simple and easy to understand, so I am very confusing that why I had that error?

Could you please give me some comments ? Thank you very much!

anhbuiask
  • 63
  • 1
  • 2
  • 8

1 Answers1

1

Add the attribute static to class Employee otherwise it's a non static inner class which needs to be instantiated from an instance of EmployeeTest, which does not exist in EmployeeTest.main.

Amir Kirsh
  • 12,564
  • 41
  • 74
  • thank you for your comment. You are right. After add the attribute `static` to the `class Employee`, my code ran very smooth. Your comment also easy to understand. – anhbuiask Aug 21 '20 at 04:08