Jan Tacci
Jan Tacci

Reputation: 3211

Accessing Private Members Of Enum Variable?

I was looking at a simple Enum example to try and brush up my skills and I noticed something that at least through up a red flag for me as I don't understand why it's allowed.

Here is a copy of the enum I was looking at:

public enum GameDuration {
    Short("30"), Medium("45"), Long("60");

    private GameDuration(String minutes) {
        this.minutes = minutes;
    }

    private String minutes;

    public String getMinutes() {
        return this.minutes;
    }

    public static GameDuration fromMinutes(String minutes) {
        if (minutes != null) {
            for (GameDuration g : GameDuration.values()) {
                if (minutes.equalsIgnoreCase(g.minutes)) {
                    return g;
                }
            }
        }
        return null;
    }
}

The part I don't understand is in the fromMinutes method and pasted below:

if (minutes.equalsIgnoreCase(g.minutes)) {

the minutes field in the enum is marked as private so how can it be accessed directly from the variable g?

Thanks

Upvotes: 0

Views: 65

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

The method fromMinutes(...) is located inside of the GameDuration class, and so private variables and methods of the class are accessible to it.

Upvotes: 1

Related Questions