When compiling several .java files with some dependency relation between them, do we need to compile them in some order?
Must a dependency be .class file? Or can a dependency be a .java file?
Specifically, when A.java depends on B.class file compiled from B.java file, but B.class hasn't been created (i.e. B.java file hasn't been compiled into B.class), can we compile A.java by specifying the directory for B.java in java -cp? Or do we need to compile B.java into B.class first, and then specify the directory for B.class in java -cp when compiling A.java?
For example, from https://dzone.com/articles/java-8-how-to-create-executable-fatjar-without-ide, ./src/main/java/com/exec/one/Main.java depends on ./src/main/java/com/exec/one/service/MagicService.java, and both haven't been compiled yet.
Why does the following compilation fail?
$ javac ./src/main/java/com/exec/one/*.java -d ./out/
./src/main/java/com/exec/one/Main.java:3: error: package com.exec.one.service does not exist
import com.exec.one.service.MagicService;
^
./src/main/java/com/exec/one/Main.java:8: error: cannot find symbol
MagicService service = new MagicService();
^
symbol: class MagicService
location: class Main
./src/main/java/com/exec/one/Main.java:8: error: cannot find symbol
MagicService service = new MagicService();
^
symbol: class MagicService
location: class Main
3 errors
Why does the following compilation succeed? How can one compile them in one javac command? How is -cp ./src/main/java used in the compilation? What happens in the compilation process?
$ javac -cp ./src/main/java ./src/main/java/com/exec/one/*.java ./src/main/java/com/exec/one/**/*.java
./src/main/java/com/exec/one/Main.java
package com.exec.one;
import com.exec.one.service.MagicService;
public class Main {
public static void main(String[] args){
System.out.println("Main Class Start");
MagicService service = new MagicService();
System.out.println("MESSAGE : " + service.getMessage());
}
}
./src/main/java/com/exec/one/service/MagicService.java
package com.exec.one.service;
public class MagicService {
private final String message;
public MagicService(){
this.message = "Magic Message";
}
public String getMessage(){
return message;
}
}