0

I'm very certain I've done this before, so I'm not sure why it's causing an error now. This is the error I get:

$ javac Zombie.java
Zombie.java:51: error: non-static variable this cannot be referenced from a static context
            array.add(new Point(p.d0-1, p.d1));
                      ^

It's pointing at where I define a new object, so am I not allowed to do this within a method call when in a static context? Do I need to define a variable and pass it in? Because that'd take more time and be much more messy....

For proper context:

  • array is of type ArrayList
  • Point is a class I defined. The constructor is called correctly.
  • p is an instance of Point. It has two fields: d0 and d1 (dimension 0 and dimension 1, to alleviate confusion with X and Y).
CaptainForge
  • 1,365
  • 7
  • 21
  • 46

1 Answers1

0

You need to declare nested classes both public and static if they are used in a static context within the non-nested class. I did this, and no longer got this error.

CaptainForge
  • 1,365
  • 7
  • 21
  • 46
  • 2
    You should take time to understand that a non-static inner class requires an instance of its enclosing type. This is because the inner class has implicit access to instance fields and methods of the enclosing type. Static inner classes cannot implicitly access those instance fields and members, so no instance is required. – Mark W Mar 21 '16 at 18:41