Reputation: 3245
i have two programs one in directory /home/redhat/Documents/java1/j1
Demo1.java
package j1;
public class Demo1
{
public void print()
{
System.out.println("hi");
}
}
and the other in directory /home/redhat/Documents/java1/j
Demo2.java
import j1.*;
public class Demo2
{
Demo2()
{
Demo1 d=new Demo1();
}
}
when i say
javac -classpath /home/redhat/Documents/java1/j1 Demo2.java
i get the following error
Demo2.java:2: package j1 does not exist
import j1.*;
^
Demo2.java:7: cannot access Demo1
bad class file: /home/redhat/Documents/java1/j1/Demo1.java
file does not contain class Demo1
Please remove or make sure it appears in the correct subdirectory of the classpath.
Demo1 d=new Demo1();
^
2 errors
i want to access instance of Demo1 in Demo2 please help.
Upvotes: 4
Views: 7932
Reputation: 76709
The classpath option specified in the command line of the javac executable is used to define the user classpath location where the compiler may find the compiled class files of types. In other words, the compiler expects compiled .class files in the user classpath.
In your case, you have a source class file, in which case you should use the sourcepath option of javac:
javac -sourcepath /home/redhat/Documents/java1 Demo2.java
javac will locate the j1 package under the user class path and hence resolve the type.
Upvotes: 0
Reputation: 11316
Your classpath is wrong. You should point to the root of any declared packages:
javac -classpath /home/redhat/Documents/java1 Demo2.java
Other previous step that I miss is the compilation of Demo1 class. Javac compiler will look for ".class" files, not ".java" ones. So before executing that you need:
javac Demo1.java
As an improvement I would suggest you that you declare your second class inside package "j" instead of default package, since it is not a good idea to have root source paths inside another root path that already contains packages.
Upvotes: 4