Class specification

I have two programs, one in the directory / home / redhat / Documents / java 1 / j1

Demo1.java

package j1; public class Demo1 { public void print() { System.out.println("hi"); } } 

and the other in the directory / home / redhat / Documents / java 1 / j

Demo2.java

 import j1.*; public class Demo2 { Demo2() { Demo1 d=new Demo1(); } } 

when I speak

 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 an instance of Demo1 in Demo2 please help.

+4
source share
2 answers

Your class path is wrong. You must point to the root of all declared packages :

 javac -classpath /home/redhat/Documents/java1 Demo2.java 

Another previous step that I skipped was compiling the Demo1 class. The Javac compiler will look for ".class" files, not ".java". Therefore, before execution it is necessary:

 javac Demo1.java 

As an improvement, I would suggest you declare your second class inside the package "j" instead of the default package, since it is not recommended to have root source paths inside another root path that already contains packages.

+4
source

The classpath parameter specified on the javac executable command line is used to determine the location of the path to the user path where the compiler can find the compiled class of type files. In other words, the compiler expects to compile .class files in the class path of the user.

In your case, you have a source code file, in which case you should use the sourcepath option for javac:

 javac -sourcepath /home/redhat/Documents/java1 Demo2.java 

javac will find package j1 in the user's path and, therefore, will allow its type.

0
source

All Articles