这是一个非常简单的问题,但我认为它有点争议。
当我编写 Java 类代码时,我使用以下顺序。
class Foo {
// static fields
// instance fields
// constructors
// methods (non-static and static methods are mixed but sorted based on their functionalities)
}
我读过一篇文章说:
(来自http://code.google.com/webtoolkit/makinggwtbetter.html#codestyle)
Java 类型应具有以下成员顺序:
嵌套类型(混合内部类和静态类是可以的)
静态字段
静态初始化器
静态方法
实例字段
实例初始化器
构造函数
实例方法
如果我按照文章,上面的顺序应该是
class Foo {
// static fields
// static methods
// instance fields
// constructors
// instance methods
}
在后者的情况下,我觉得在构造函数之前有一些方法是不舒服的。 哪个是使用更广泛的约定?
最佳答案
我相信 Sun(现在是 Oracle)的 Java 编码标准被更广泛地使用。这也是您目前正在使用的。
来自 Code Conventions for the Java TM Programming Language :
3.1.3 Class and Interface Declarations
The following table describes the parts of a class or interface declaration, in the order that they should appear.
- Class/interface documentation comment ( /*.../)
class
orinterface
statement- Class/interface implementation comment ( /.../), if necessary
- Class (
static
) variables- Instance variables
- Constructors
- Methods
关于关于静态方法的 Java 编码约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7530535/