Search code examples
javavariable-namespackage-name

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


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?


Solution

  • 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.