Should Java member enum types be capitalized?

好久不见. 提交于 2019-12-05 17:14:04

问题


Anal question here: we have Java enums which are their own classes, and enums which are members of a class:

public enum reportType { ...

Every time I see this it jars me* because when I see it used in a declaration, it's a type, and types should be capitalized. But when I try to capitalize it, Eclipse warns me that I shouldn't capitalize field names. I figure Eclipse probably knows the official Java conventions better than I do, but it just doesn't seem right. Even flipped through the Java conventions doc, but didn't see this issue referenced.

  • no pun intended

回答1:


If they are their own class start with upper case, if they are members lower case.

public enum ReportType { XML, TEXT, HTML };

public class MyClass
{
     ReportType defaultReport = ReportType.XML; 
}



回答2:


Enums are a type and the enum name should start with a capital. Enum members are constants and their text should be all-uppercase.




回答3:


Are you sure you are using the default settings? Because generally enums are indeed capitalized. Variables holding enum values should not start with a cap though.

public enum State {
  UNINITIALIZED,
  INITIALIZED,
  STARTED,
  ;
}

private State state;

private void start() {
  state = State.UNINITIALIZED;
  ...
}
`.

You may use static imports to get rid of the State. part as well, although generally I think it is better to leave it be. The enum values are constants and should be in CAPS. I've seen people change fields in enum constants during runtime, and that is not what you want (except for lazy instantiation within the class itself now and then).




回答4:


Even flipped through the Java conventions doc, but didn't see this issue referenced.

The Java conventions doc hasn't been updated in 10+ years. Basically since Java 1.1.




回答5:


In Java, names of (non-primitive) types are usually written in PascalCase. Since an enum (as a class) defines a type, it is usual to write them also in PascalCase:

enum MyEnumInPascalCase { ... }


来源:https://stackoverflow.com/questions/8143995/should-java-member-enum-types-be-capitalized

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