I am trying to understand Java packages.
I have two classes, A.java and B.java, in the same package. Class A references class B.
Both have package statements package world.example;
and are saved in a directory.../world/example/
.
B compiles ok, but when attempting to compile A, javac fails to find the classfile for B.
I have tried running javac from the parent of /world
as well as from /example
. I have searched many answers both here and elsewhere, to no avail. Most questions on similar topics seem to have much extraneous code and information, so I have tried to distil my issue down to its bare bones but still cannot see what I am missing.
Addendum: if I remove the package statements, both classes compile ok provided I specify the classpath when compiling A, thus: javac -classpath . A.java
.
Code follows:
package world.example;
public class A {
public static void main(String[] args) {
String msg = B.getMessage();
System.out.println(msg);
}
}
...and...
package world.example;
public class B {
protected static String getMessage() {
return "Hello world!";
}
}
...and the output from javac...
17-04-17◆23:03 example »javac B.java
17-04-17◆23:04 example »javac A.java
A.java:5: error: cannot find symbol
String msg = B.getMessage();
^
symbol: variable B
location: class A
1 error
17-04-17◆23:04 example »javac -classpath . A.java
A.java:5: error: cannot find symbol
String msg = B.getMessage();
^
symbol: variable B
location: class A
1 error
I have two classes, A.java and B.java, in the same package. Class A references class B
You have to do the practical way of separation to separate your .java files from .class files.
Repeat the whole compiling process with me.
First, use this command while you compiling .java file in CMD in order to separate .java files from .class files and to avoid confusion.
javac -d Target_Location Filename.java >>>> Spaces are important
Target_location = C:\blah\blah << where you want your packages/classes directory to be in.
After compiling you're going to get your class files on the Target_Location which you chose before. So, now you have to change your classpath environment variable to that target location because you have provided a third party packages.
execute and see.
how to set your classpath in CMD.
set classpath = c:\blah\blah;