Java 类中的私有枚举位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19338112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:15:14  来源:igfitidea点击:

Private enum location inside a class in Java

javaenumsinner-classes

提问by miviclin

When declaring an enum inside a class in java I've seen these 2 approaches:

在 java 中的类中声明枚举时,我看到了这两种方法:

1)

1)

public class MyClass {

    private enum MyEnum {
        A, B, C;
    }

    /* Static fields */

    /* Instance variables */

    /* Methods */
}

2)

2)

public class MyClass {

    /* Static fields */

    /* Instance variables */

    /* Methods */

    private enum MyEnum {
        A, B, C;
    }
}

Which one is the most used? Is there any convention for this?

最常用的是哪一种?是否有任何约定?

采纳答案by Joel Christophel

Generally in Java, nested data types (e.g. classes, enums) go at the bottom of a file.

通常在 Java 中,嵌套数据类型(例如类、枚举)位于文件的底部。

However, for short, private enums like the one you posted (which feel more like fields), I'd go with #1.

但是,简而言之,像您发布的那样的私有枚举(感觉更像是字段),我会选择 #1。

For longer enums, I'd either go with #2 or put them in a separate file.

对于更长的枚举,我要么选择 #2,要么将它们放在一个单独的文件中。

回答by Troubleshoot

There isn't any convention used for it, but from what I've seen, example 1 is used more often. I personally place them in that way too.

没有使用任何约定,但从我所见,示例 1 的使用频率更高。我个人也以这种方式放置它们。

回答by Rupesh

Java does not have a typedefstatement (as in C and C++). To declare new types in Java, you declare a new class; then variables can be declared to be of that class's type. Also Java uses Forward references, java compiler is smarter than the C compiler, in that it allows methods to be invoked before they are defined. This eliminates the need to declare functions in a header file before defining them in a program file, as is done in C.

Java 没有typedef语句(如在 C 和 C++ 中)。要在 Java 中声明新类型,您需要声明一个新类;然后可以将变量声明为该类的类型。Java 也使用前向引用,Java 编译器比 C 编译器更聪明,因为它允许在定义方法之前调用它们。这消除了在程序文件中定义函数之前在头文件中声明函数的需要,就像在 C 中所做的那样。

I can place my enumanywhere and can access it from anywhere. Refer example.

我可以把我的enum任何地方都可以从任何地方访问它。参考例子。

class CheckEnum{

    private void method1() {
        System.out.println(enumTest.test1);    
    }       
    private enum enumTest{
        test1
    }       
    private void method2() {
        System.out.println(enumTest.test1);
    }
}

I have checked and both method method1and method2has access to enumTest.

我已经检查了这两种方法method1并且method2可以访问enumTest.

回答by Noris

There is nothing wrong with either of them. It's more a matter of opinion but I would go go #1.

他们中的任何一个都没有错。这更多是一个意见问题,但我会去#1。