How do I compile and run the following programs:
Test1.java:
package A;
public class Test1
{
public int a = 1;
}
Test2.java:
package B;
import A.*;
public class Test2
{
public static void main(String [] args)
{
Test1 obj = new Test1();
System.out.println(obj.a);
}
}
I’m new to packages.
If I compile using javac *.java
and manually create dir A, copy Test1.class into it and manually create dir B and copy Test2.class into it and then run java B.Test2 it works. I’m sure this is not the right way of doing it. Please suggest.
You need to keep your java files in the correct directory structure:
It’s usually sufficient to only invoke
javacon your main class, as all dependencies will be handled automatically. After I sayjavac B/Test2.java, it looks like this:And I can run the program with
java B.Test2.If it’s not enough just to run
javacon your main class, you’ll probably need a build system.