简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM