Project directory:
Project
-[other directories]
-bin
--A.java
--B.java
Class A source code:
package bin;
public class A{
public static void main(String[] args){
B use=new B("Hello");
use.run();
}
}
Class B source code:
package bin;
public class B{
static String x=null;
public B(String text){
x=text;
}
public static void run(){
System.out.println(x);
}
}
There was no error when I compiled B.java, when I tried to compile A.java, I got:
A.java:4: error: cannot find symbol
B use=new B("Hello");
symbol: class B
location: class A
search.java:4: error: cannot find symbol
B use=new B("Hello");
^
symbol: class B
location: class A
By the way, I am not using an IDE to compile this, I just edited the files with Geany and nano, then tried to compile them from the terminal with javac.
CodePudding user response:
As pointed out by @Alex, you are most likely executing javac command inside bin folder. The right way to compile the program in your situation is to run the javac command int project folder
javac bin/A.java
and to run
java bin/A
CodePudding user response:
- Assuming the current working directory is
Project
, the code shold be compiled as:
Project> java bin/*.java
This compiles all classes in bin
into the same directory:
Project> dir bin
13.02.2022 18:20 <DIR> .
13.02.2022 18:20 <DIR> ..
13.02.2022 18:20 346 A.class
13.02.2022 18:14 117 A.java
13.02.2022 18:20 478 B.class
13.02.2022 18:14 154 B.java
4 files 1 095 bytes
- Run the code providing the package name in the class
bin.A
:
Project> java bin.A
Hello
However, to avoid mess in the source folder bin
where the .class
files are created by the compiler along with the .java
source files, it would be better to provide a separate directory (e.g. classes
) and refer it providing classpath parameter -cp
:
Project>javac -d classes bin/*.java
Project>java -cp classes bin.A
Hello