Can I do a static import of a private subclass?

I have an enumeration that is private and not open to outside the class. In any case, can I do a static import of this type, so I don’t need to enter an enumeration type every time? Or is there a better way to write this? Example:

package kip.test; import static kip.test.Test.MyEnum.*; //compile error public class Test { private static enum MyEnum { DOG, CAT } public static void main (String [] args) { MyEnum dog = MyEnum.DOG; //this works but I don't want to type "MyEnum" MyEnum cat = CAT; //compile error, but this is what I want to do } } 
+6
java syntax enums static-import
source share
6 answers

Or is there a better way to write this?

If your main goals are to reference elements without their enumerated name identifier and maintain this list privately, you can opt out of the enum type altogether and use regular private static constants.

+3
source share

You can use the access level without a modifier, i.e.

 enum MyEnum { DOG, CAT } 

MyEnum will not be displayed for classes from other packages or from any subclass. This is the closest private form, but allows you to explicitly not reference MyEnum .

+4
source share

It may (or not) be sensible to move part of the code into (static) enumeration methods.

If you click, you can duplicate static fields in the outer class.

 private static final MyEnum CAT = MyEnum.CAT; private static final MyEnum DOG = MyEnum.DOG; 

Icky, but an opportunity.

+2
source share

Given that you can access the field completely, I would say that this is a compiler error (or language specification) that you cannot statically import.

I suggest you do package protection with an enumeration.

+1
source share

No, that's almost what private about.

0
source share

You can simply write your code inside the listing itself.

 public enum MyEnum { DOG, CAT; public static void main(String[] args) { MyEnum dog = MyEnum.DOG; // this works but I don't want to have to type // MyEnum MyEnum cat = CAT; // compile error, but this is what I want to do } } 

Another place where private enumerations can be links without their class is in the switch statement:

 private static enum MyEnum { DOG, CAT } public static void main(String[] args) { MyEnum e = null; switch (e) { case DOG: case CAT: } } 
0
source share

All Articles