What difference it make when I make a constructor of enum private or default?

Darshit :

I have a enum class as below:

public enum TargetingName {

CONTENT("Content", "Content Targeting"), TECHNOLOGY("Technology", "Technology Targeting");

private TargetingName(String textToSelect, String textDisplayed) {
        this.textToSelect = textToSelect;
        this.textDisplayed = textDisplayed;
    }

    private String textToSelect;
    private String textDisplayed;

    public String getTextDisplayed() {
        return textDisplayed;
    }

    public String getTextToSelect() {
        return textToSelect;
    }
}

If I don't write private in constructor of enum does it make it default? If yes, what would be the difference? If No, then how to make a default constructor?

Andrew Tobilko :

8.9.2. Enum Body Declarations

In an enum declaration, a constructor declaration with no access modifiers is private.

It wouldn't make any difference except you would need to write an extra word.

I saw developers putting private to make it more explicit (to emphasise the fact you can't use an enum constructor outside the enum). I find it unnecessary.

If I don't write private in constructor of enum does it make it default?

If by "default" you mean private, yes.

If by "default" you mean package-private, no. Neither public nor protected is allowed. Enum constructors are always private.

8.9.2. Enum Body Declarations

It is a compile-time error if a constructor declaration in an enum declaration is public or protected (§6.6).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164012&siteId=1
Recommended