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.

Who is Participating?
To answer your questions:

for #1)  In which directory do I copy the class file so that JAVAC can see it.
Ans: Copy your class file into the <Java Home>/lib subdirectory

for #2. What do I put in import statement.
Ans:  import <class name>;
Example: if your class filename is foo.class, the import statement is:

import foo;
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:

2. not package structured
               ...your classes

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

           ...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
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
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

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.
> 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.
ltdang7Author Commented:
Worked, thanks.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.