关于静态方法的 Java 编码约定

标签 java coding-style convention

这是一个非常简单的问题,但我认为它有点争议。

当我编写 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.

  1. Class/interface documentation comment ( /*.../)
  2. class or interface statement
  3. Class/interface implementation comment ( /.../), if necessary
  4. Class (static) variables
  5. Instance variables
  6. Constructors
  7. Methods

关于关于静态方法的 Java 编码约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7530535/

相关文章:

java - 编码风格有问题

c# - 检查 'null'

java - 如何在java中以表格格式显示linkedhashmap类型的列表

java - 使 Spring Hibernate 线程安全。最好的安慰

java - 如何以我想要的方式/格式使用 log4j?

c++ - 奇怪的图案 : all functions/methods return error-code using the same type in C++

java - 在内存中加载文本文件的最快/最干净的方法

sql - SQL 电子邮件字段应该有多长?

python - 有条件地设置和有条件地使用变量 python

java - 如何使用 RabbitMQ 和 AMQP 锁定应用程序