How can I refer to an enum variable from a static context?

    if(array[3][3].getCall() == false && array[3][3].getUser() == Car.user.NONE )
    {
        array[3][3] = new Car('s', Car.user.USER, false);
        aCounter++;

        System.out.println("everything is fine");

    }

      

this bit of code gives me: error: non-static variable user cannot refer to static context.

public class Car
{

    public enum User { USER, COMP, NA };

    private char object;
    public User user;
    private boolean call;

    public Car(char object, User user, boolean call)
    {
        this.object = object;
        this.user = user;
        this.call = call;
    }
}

      

The Enum is public because otherwise I get "custom access errors". I know that an enum is a non-static variable declared inside a constructor, so I think there is an error here, but I don't know how to fix it.

+3


source to share


1 answer


The problem has nothing to do with enum variables and everything to do with static fields and classes versus non-static fields and classes. Please note that when you write

Car.user.NONE

      

Car.user

refers to a named field user

in the class Car

, but Car.user

is an instance variable, not static. Hence the error:



non-static variable user cannot be referenced from a static context

To fix this, just change Car.user

to Car.user

so that the expression refers to the field enum User

and not User user

.

if(array[3][3].getCall() == false && array[3][3].getUser() == Car.User.NONE )
{
    array[3][3] = new Car('s', Car.User.USER, false);
    aCounter++;

    System.out.println("everything is fine");
}

      

+6


source







All Articles