prog
prog

Reputation: 150

How do I reference 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 be referenced from a 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;
    }
}

Enum is public, because I get "user has private access errors" otherwise. I know that enum is a non-static variable declared inside a constructor, so I am thinking that this is where the error comes from, but I have no clue as to how to fix it.

Upvotes: 3

Views: 2638

Answers (1)

Matt Ball
Matt Ball

Reputation: 359816

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

Car.user.NONE

Car.user refers to the field named user on the Car class – but Car.user is an instance variable, not a static one. 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 expression refers to the enum User rather than the User user field.

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");
}

Upvotes: 6

Related Questions