Dante Hoyte
Dante Hoyte

Reputation: 333

does an imported class have to be in a directory within the parent directory?

So I have a program we'll call A.java.

I'm trying to import my own predefined classes into this program by setting up a classpath to these classes defined in a package called helpers.

I've compiled the two classes in a class called helpers within the helpers package. The helpers source code is in a folder called helpers. I hope this isn't bad naming.

Anyways, how can I set up the classpath so A.java can get a hold of these classes?

My directories are laid out like this:

Java dir:
 -helpers
   -helpers.java
   -helpers.class
 -A
   -A.java
   -A.class

Upvotes: 2

Views: 268

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

First of all, you should respect the Java naming conventions. Classes start with an uppercase letter. Packages are all in lowercase.

You should also avoid putting the .class files in the same dirctory structure as the .java files.

And the directory structure must match exactly with the package structure, in the sources and in the classes.

So, if you have 2 classes a.A and helpers.Helpers, thr structure should be the following:

project
  src
    a
      A.java
    helpers
      Helpers.java
  classes
    a
      A.class
    helpers
      Helpers.class

To be able to compile the source files, go into the project directory, and type the following command:

javac -d classes -cp classes src/a/A.java src/helpers/Helpers.java

To be able to run the a.A class, go into the project directory, and type the following command:

java -cp classes a.A

Upvotes: 2

Related Questions