变量名是否有任何限制,以免与包名冲突?

is there any restriction on variable name so that it should not conflict with package name?

假设,我在测试包中有一个测试class:

package test;

public class Test {

    private static int clarying=20;

    public static void main(String[] args) {
        clarying.Product.display(clarying); // this line is giving error 
                                            // The primitive type int of
                                            // clarying does not have a field Product
    }
}

假设,我有另一个 class 克拉里包装的产品:

package clarying;

public class Product {
    private static int test;

        public static void display(int data) {
            test = data;
            System.out.println(test);
        }
}

我已经编译了产品 class,现在我正在尝试编译测试 class,但它抛出了一个编译器错误:

 Exception in thread "main" java.lang.Error:
 Unresolved compilation problem:  
 The primitive type int of clarying does not have a field Product
  at test.Test.main(Test.java:5)

问题符合:

clarying.Product.display(clarying);

因为Testclass中变量名clarying,与包名clarying相同。因此,当我写 clarying.Product 时,它正在搜索 Product 字段 clarying class-变量。

我只想澄清一下:是否有任何规则禁止定义与包同名的变量?

您可以在这里阅读完整的规则:6.4.2. Obscuring

A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type, or a package. In these situations, the rules of §6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package. Thus, it is may sometimes be impossible to refer to a visible type or package declaration via its simple name. We say that such a declaration is obscured.

是的,有规定。编译器认为您指的是字段 clarying。它无法知道您实际上是指包,而且我认为没有办法告诉它您指的是包(它必须类似于 this 但意味着包根而不是当前实例)。由于该字段只是一个 int,您将得到您遇到的错误。

如果你想规避,只需导入 Product class:

package test;

import clarying.Product;

public class Test{
    private static int clarying=20;

    public static void main(String[] args) {
        Product.display(clarying);
    }
}

但是,您可能应该重新考虑变量的名称,因为这可能会造成相当大的混乱,尤其是当其他人试图阅读您的代码时。