Originally posted by Ganesh:
package com.foo;
public class MyClass { public void hi() { } }
//import com.foo.MyClass; // either import will work //LINE1
import com.foo.*; //LINE-2
public class Another {
void go() {
MyClass m1 = new MyClass(); // alias name //LINE-3
//com.foo.MyClass m2 = new com.foo.MyClass(); // full name //LINE-4
m1.hi();
//m2.hi();
}
}
The above code compiles for me if i do the following steps:
1. Compile javac -d . MyClass.java
2. If MyClass.java and Another.java are in the same directory then rename
MyClass.java to say MyClass_bak.java
3. Compile javac Another.java
The problem seems to be the presence of MyClass.java in the current directory from where Another.java is being compiled.
As per my understanding the reason is as follows:
When a compiler compiles a class in this case Another.java, then it first searches for the referenced class files in the appropriate paths mentioned in the classpath environment variable. (NOTE: My classpath was set to look in current directory first using dot ".")
Since my current directory contained MyClass.java the compiler got confused and thought it was the MyClass.class file and on searching for byte codes it got plain text source code and complained as follows:
Another.java:5: cannot access MyClass
bad class file: .\MyClass.java
file does not contain class MyClass
Please remove or make sure it appears in the correct subdirectory of the classpath.
MyClass m1 = new MyClass(); // alias name //LINE-3
^
1 error
So the compiler is not able to resolve the correct class file and got confused.
But if you specify the fully qualified name of the class in the import statement viz.
import com.foo.MyClass then the compiler is not confused even if MyClass.java exists in the same directory as Another.java
I don't know if it's correct behaviour or a limitation of compiler.
Anybody got a clearer idea please share with us
[ November 29, 2008: Message edited by: Harvinder Thakur ]