变量名称是否有任何限制,以便它不与程序包名称冲突? [英] is there any restriction on variable name so that it should not conflict with package name?

查看:111
本文介绍了变量名称是否有任何限制,以便它不与程序包名称冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose, I have one Test class in test package:

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

假设,我在声明包中还有另一个类Product:

Suppose, I have another class Product in clarying package:

package clarying;

public class Product {
    private static int test;

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

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

I have compiled the Product class and now I am trying to compile the Test class but it is throwing a compiler error:

 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 类变量

Because the variable name is clarying in Test class, is the same as the package name clarying. So, when I am writing clarying.Product it is searching for a field Product inside of the clarying class-variable.

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

I just want to clarify: Is there any rule against defining a variable with the same name as a package?

推荐答案

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

You can read the complete rules here: 6.4.2. Obscuring

在可能将其解释为变量,类型或包的名称的上下文中,可能会出现一个简单的名称.在这些情况下,第6.5节的规则指定将优先于类型选择变量,并优先于包选择类型.因此,有时可能无法通过其简单名称引用可见类型或程序包声明.我们说这样的声明是模糊的.

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.

这篇关于变量名称是否有任何限制,以便它不与程序包名称冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆