sharath sharath - 14 days ago 4x
Java Question

Must a class name be fully qualified when we already set -classpath to locate that file?


I have a class called ProgA

package test;
public class ProgA
public static void main(String[] args)
ProgB pb = new ProgB();

Now I have the ProgB like below:

package test2;
public class ProgB
public void callMe()
System.out.println("inside callme");

After compiling its class file is generated in the test2 package. Now when I try to compile using this command:

javac -cp C:\Users\MyName\Desktop\test2

I get the error that it cannot find ProgB.
My question is why cant java look inside the class path to find ProgB.class file and compile my successfully? The code works fine when I specify the fully qualified class name of ProgB inside code and run with the classpath set to
-classpath C:\Users\MyName\Desktop
. Why to have the fully quilified name when I am already specifying the full class path to find ProgB. I am not clear with that concept of classpath and fully qualified class name. Please explain me. Thank you


In order to use a class from another package, you need to either use the fully qualified class name, or have an import statement. This is a .java source code requirement. It can't be fixed simply by fiddling with the compiler's classpath.

Without an import statement, unqualified names are assumed to belong to the current source file's package. If you're in a package test file, the identifier ProgB will match test.ProgB but not test2.ProgB. The compiler won't search other packages unless you tell it to.