简体   繁体   中英

Compiling error while compiling two java files in the same package that use each other

Suppose we have two.java files in the same directory.

Test.java:

public class Test {
    public void func() {
        System.out.println("Hello World");
    }
}

Main.java:

public class Main {
    public static void main(String args[]) {
        Test t = new Test();
        t.func();
    }
}

If I write in the command line: javac Main.java
it creates the Main.class and automatically creates Test.class and for running this program I use: java Main

but when I add package myPack statement in the first line of two files everything changes. and the structure of the files is as follows:

myPack
├── Main.java
└── Test.java

If I write javac Main.java the compiler says:

Main.java:5: error: cannot find symbol Test t = new Test();

and I should compile both of them at the same time. (javac Main.java Test.java)

Question 1) Why it happens?

Question 2) When I compiled both files I cant run program with java Main.

(Error: Could not find or load main class Main ).

What's the problem?

Question 3) I read somewhere you should compile and run this from the parent directory like this: javac myPack/Main.java (it automatically creates Test.class file) and then java myPack.Main . this way the program works properly. but why should we compile and run programs from the parent directory with this syntax?

Try this for compiling

# compile all files .java in folder ./myPack and outputing in ./folder-compiled
javac -d folder-compiled $(find ./myPack -name '*.java')

So you can run all compiled class with this

# run all Main.class already compiled in ./folder-compiled
java -cp folder-compiled Main

this example above will work because I'm considering your classpath is in myPack/* and you are not working with modular classpath jdk9+ in other way may be diferent

the other simple and easy way is working with building tools such as gradle or maven

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM