I'm trying to import Bar.java
into Foo.java
, where my directory is structured like this:
.
└─bar
└─Bar.java
└─foo
└─Foo.java
So I create Bar.java
:
package bar;
public class Bar {}
and Foo.java
:
import bar.Bar;
public class Foo {}
I run javac
from the foo
directory:
javac Foo.java -cp ../bar
and receive the error:
Foo.java:1: error: package bar does not exist
My understanding was that the -cp
option should be used to point towards the required class (Bar.java
). Could someone shed some light on what I'm doing wrong?
CodePudding user response:
Package bar does not exist because the prompt or terminal "working directory" is inside foo.
Easiest, make a folder java2 and put both folders in it and use use the storage folder as "system working directory" for terminal or prompt, However, normal "package" hierarchies compiled together are both in a top level starting directory tree.
E.g.
/com/foo/ and /com/bar
So your package would look com.foo and com.bar Put the com folder in the java2(simply a name you can use any name for the storage folder)folder. Your import statement at the top of the class files should have the com directory added to import the other file. Just command inside java2 folder
javac /com/foo/Foo.java
-cp is for specifying to include dependent .jar libraries for the compilation.
If Foo does not import Bar then it will be required to be separately compiled the same way as Foo.
When framework API libraries are made its the user program requires to mark a starting point to unload the jar or look for a package folder and is traditionally "com", however, it does not distinguish which API until a folder lower so your package folder really should be structured
/com/mypersonalapi/foo /com/mypersonalapi/bar
com.mypersonalapi.foo com.mypersonalapi.bar
CodePudding user response:
You need to give like this:
javac Foo.java -cp ..
When you give classpath as shown in your question, it expects the package "bar" under the folder "bar"; which is not intended.