Do I need to define an enum as 'public' in its own file so it can be recognized outside its own package?

て烟熏妆下的殇ゞ 提交于 2020-01-03 13:34:24

问题


I have two packages - x and y.

x contains the Student class and the Grade enum.

y contains the Klass class.

Why is the type Student.Grade.C not recognized in the Klass class in package y?

Do I need to define it in its own file and make it public?

package x;

enum Grade { A, B, C, D, F, INCOMPLETE };

public class Student {

// blah, blah, member variables, getters, setters, constructors    

}


package y;

public class Klass {

 // This enum type is not recognized in this package
 public static final MINIMUM_GRADE = Student.Grade.C; 

}

回答1:


Yes, you do have to declare that enum public. You shouldn't have to have it in its own file.

You would access just like your example Student.Grade.C;

You could import Student.Grade and just use C in your code.




回答2:


By not using public, protected or private, the Grade enum has the default access level - meaning only other classes in the same package can use it.



来源:https://stackoverflow.com/questions/3798045/do-i-need-to-define-an-enum-as-public-in-its-own-file-so-it-can-be-recognized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!