Java class 中方法的静态最终常量的位置

Location of static final constants for method in Java class

假设我有一个 class 方法,它使用一些静态最终变量作为常量,但 class 中没有其他方法使用它们。

例如,具有平衡方法的 AVLTree class 使用这些常量来描述旋转的平衡因子

private static final int L_HEAVY = 2;
private static final int LL_HEAVY = 1;
private static final int R_HEAVY = -2;
private static final int RR_HEAVY = -1;

根据 Java 编码约定(例如 Oracle 的代码约定),将这些常量放在什么地方最好?

public class AVLTree {
    private Node root;
    // (1) Here, among members, right after class declaration ?

    public AVLTree() {
        root = null;
    }       

    ...

    // (2) Here, just above the method that uses them?

    private Node balance(Node node) {
        // (3) Here, inside the method that uses them?

        if (height(node.left) - height(node.right) == L_HEAVY) {
            if (height(node.left.left) - height(node.left.right) == LL_HEAVY) {
                ...
            }
        }

        if (height(node.left) - height(node.right) == R_HEAVY) {
            if (height(node.right.left) - height(node.right.right) == RR_HEAVY) {
                ...
            }
        }

        return node;    
    }

    ...
}

如果您确实知道 none 您的方法现在或将来会使用这些变量,则可以将它们设为方法内部的局部变量。

但是,如果变量将来有可能被其他方法使用(在 class 内部或外部 class),请将变量设为 public 并将它们放在顶部。

放置不会影响编译,但最好与定义变量和方法的位置保持一致。

最好将所有常量放在 class 的顶部。

例如,Sun 的代码公约确定了 this class file 组织。