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

时间秒杀一切 提交于 2019-12-12 03:07:19

问题


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

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

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)

issue is in line:

clarying.Product.display(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?


回答1:


You can read the complete rules here: 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.




回答2:


Yes, there is a rule. The compiler thinks you mean the field clarying. It has no way of knowing that you actually mean the package and I don't think there is a way to tell it that you mean the package (which would have to be something like this but meaning the package root instead of the current instance). Since the field is just an int you'll get the error that you have.

If you want to circumvent that just import the Product class:

package test;

import clarying.Product;

public class Test{
    private static int clarying=20;

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

However, you should probably reconsider the name of your variables, since this can cause quite a bit of confusion, especially when others are trying to read your code.



来源:https://stackoverflow.com/questions/28498915/is-there-any-restriction-on-variable-name-so-that-it-should-not-conflict-with-pa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!