Java问题:无法访问EmployeeTest类型的封闭实例。

huangapple go评论107阅读模式
英文:

Java problem : No enclosing instance of type EmployeeTest is accessible

问题

  1. public class EmployeeTest {
  2. public static void main(String[] args) {
  3. Employee[] staff = new Employee[1];
  4. staff[0] = new Employee("Carl Cracker", 75000);
  5. for (Employee e : staff)
  6. System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
  7. }
  8. class Employee {
  9. private String name;
  10. private double salary;
  11. public Employee(String n, double s) {
  12. name = n;
  13. salary = s;
  14. }
  15. public String getName() {
  16. return name;
  17. }
  18. public double getSalary() {
  19. return salary;
  20. }
  21. }
  22. }

抱歉,当我运行代码时,结果是:

  1. 类型EmployeeTest的封闭实例不可访问。 必须使用类型EmployeeTest的封闭实例限定分配(例如,x.new A(),其中xEmployeeTest的实例)。

我确信我的代码非常简单易懂,所以我对为什么会出现这个错误感到非常困惑。

您能否给我一些建议?非常感谢!

英文:

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.

  1. public class EmployeeTest {
  2. public static void main(String[] args){
  3. Employee[] staff = new Employee[1];
  4. staff[0] = new Employee("Carl Cracker", 75000);
  5. for (Employee e : staff)
  6. System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
  7. }
  8. class Employee
  9. {
  10. private String name;
  11. private double salary;
  12. public Employee(String n, double s)
  13. {
  14. name = n;
  15. salary = s;
  16. }
  17. public String getName()
  18. {
  19. return name;
  20. }
  21. public double getSalary()
  22. {
  23. return salary;
  24. }
  25. }
  26. }

Unfortunately, when I ran my code, the result is

  1. 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!

答案1

得分: 1

class Employee添加属性static,否则它是一个非静态内部类,需要从EmployeeTest的实例化对象中实例化,而这个对象在*EmployeeTest.main*中是不存在的。

英文:

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.

huangapple
  • 本文由 发表于 2020年8月21日 11:51:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63516267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定