假设我在测试包中有一个测试类:
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
}
}
假设,我在 clarying 包中有另一个类 Product:
package clarying;
public class Product {
private static int test;
public static void display(int data) {
test = data;
System.out.println(test);
}
}
我已经编译了 Product 类,现在我正在尝试编译 Test 类,但它引发了编译器错误:
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 ,所以和包名 clarying 是一样的。因此,当我编写clarying.Product时,它正在搜索clarying类变量内的字段Product 。
我只是想澄清一下:是否有任何规则反对定义与包同名的变量?