How do I compile and run the following programs:
Test1.java:
package A;
public class Test1
{
public int a = 1;
}
Test2.java:
you should keep your .java files in directory structure matching your package structure
so Test1.java should go in directory A so Test2.java should go in directory B
You need to keep your java files in the correct directory structure:
A/Test1.java
B/Test2.java
It's usually sufficient to only invoke javac
on your main class, as all dependencies will be handled automatically. After I say javac B/Test2.java
, it looks like this:
A/Test1.class
A/Test1.java
B/Test2.class
B/Test2.java
And I can run the program with java B.Test2
.
If it's not enough just to run javac
on your main class, you'll probably need a build system.
There's nothing wrong with the way you are compiling, it's just cumbersome but certainly not wrong.
That being said, create a src directory to store your .java files, keeping your directory structure coherent with the package structure of your classes. In this case you would have src directory and inside it, directory A and directory B. Inside A put Test1.java and inside B put Test2.java
Then:
javac B/Test2.java
Why Test2.java? Because it depends on A, then the compiler is smart enough to first compile A/Test1.java and then B/Test2.java. At this point you have each .class files inside A and B
To run it:
java B.Test2
The compiler will create directories called A and B and place the .class files within them.
You should not need to copy the class files manually into their package directories, and it will probably not work if you do that.
This isn't a direct answer to your question but you might want to start thinking about using an IDE (others suggested ant). I would recommend jcreator if you are just starting out or Eclipse if you want something good.