Link to home
Start Free TrialLog in
Avatar of ltdang7
ltdang7

asked on

Importing my own class files

I want to be able to import a class so that I can use it's methods that sombody else has created.

1. In which directory do I copy the class file so that JAVAC can see it.
2. What do I put in import statement.

Thanks.
Avatar of Ovi
Ovi

if you want to import only a class and not a package structured class, you must put that class at the same level with your package start point. The import statement is import aClass.
Suposing you whish to use a class A.class which is not part of any package. You have two cases :
1.your project is package structured, A.class should fit like this:

  c:\Project
            A.class
            \com
                \project
                        ...classes
2. not package structured
   c:\Project\
               A.class
               ...your classes


The simpliest way is to put the class (archive) in the classpath at both compilation and execution. Supposing you have following structure :

c:\Project
          \lib
              A.class
              xyz.jar
           ...your classes or package structure

the compilation&execution of your classes should be done like :

javac -classpath .;c:\Projects\lib\xyz.jar;c:\Projects\lib\A.class; *.java

java -cp c:\Projects\lib\xyz.jar;c:\Projects\lib\A.class; YourClass
Avatar of Mick Barry
The classpath should include the directory, NOT the class name:

javac -classpath c:\Projects\lib\xyz.jar;c:\Projects\lib\ *.java

java -cp c:\Projects\lib\xyz.jar;c:\Projects\lib\ YourClass
And if your sources are in c:\Projects then you may want to use the -d option during compilation so the class files are placed in the lib directory:

javac -d c:\Projects\lib -classpath c:\Projects\lib\xyz.jar;c:\Projects\lib\ *.java

Or alternately include c:\Projects in your classpath.
ASKER CERTIFIED SOLUTION
Avatar of jodear
jodear

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
> Copy your class file into the <Java Home>/lib

Not only is this unnecessary but the classes will also not be seen by javac if placed in this directory. Except of course you explicitly include this directory in your classpath, but this is true of ANY subdirectory.
If the class is not a part of a package then the easiest thing to do is put it in the same directory as the source files you are compiling.
Avatar of ltdang7

ASKER

Worked, thanks.