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?
You can read the complete rules here: 6.4.2. Obscuring
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 likethis
but meaning the package root instead of the current instance). Since the field is just anint
you'll get the error that you have.If you want to circumvent that just import the
Product
class: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.