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?
cd ..and thenjavac myPack/Main.java. NB it is customary to use only lowercase in package names. Don't ask me why.