【问题标题】:is there any restriction on variable name so that it should not conflict with package name?变量名是否有任何限制,以免与包名冲突?
【发布时间】:2015-02-13 11:47:56
【问题描述】:

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

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
    }
}

假设,我在 clarying 包中有另一个类 Product:

package clarying;

public class Product {
    private static int test;

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

我已经编译了 Product 类,现在我正在尝试编译 Test 类,但它引发了编译器错误:

 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);

因为变量名在Test类中声明,所以和包名一样声明。因此,当我编写 clarying.Product 时,它正在 clarying 类变量中搜索字段 Product

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

【问题讨论】:

    标签: java variable-names package-name


    【解决方案1】:

    您可以在此处阅读完整的规则:6.4.2. Obscuring

    一个简单的名称可能出现在它可能被解释为变量、类型或包的名称的上下文中。在这些情况下,§6.5 的规则指定将优先选择变量而不是类型,并且将优先选择类型而不是包。因此,有时可能无法通过其简单名称来引用可见类型或包声明。我们说这样的声明是模糊的。

    【讨论】:

    • 感谢您的链接,我得到了我正在搜索的任何内容。
    【解决方案2】:

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

    如果你想绕过它,只需导入 Product 类:

    package test;
    
    import clarying.Product;
    
    public class Test{
        private static int clarying=20;
    
        public static void main(String[] args) {
            Product.display(clarying);
        }
    }
    

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    相关资源
    最近更新 更多