is there any restriction on variable name so that

2019-09-06 16:59发布

问题:

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.