Re: Issues with package declarations
ankur wrote:
My NullTest.java contains:
package forpackagetest;
public class NullTest {
....
My thisisatest.java contains:
import forpackagetest.*;
public class thisisatest {
....
So u [sic] r [sic] saying that I should create forpackagetest folder
under C:\Java Files manually.
That's "you are", not "u r".
Arne Vajh??j wrote:
Yes.
ankur wrote:
Then what would be the use of :
C:\Java Files>javac -d . NullTest.java
command ?
To compile NullTest.java. But see my comments below.
This does not make sense to me because I thought that -d option can
create the package subdirectory for you and to instantiate a class
object you only needed the .class files (I am instantiating NullTest
object in thisisatest ).
Yes, but you need those .class files *in the class path*.
I started off with :
C:\Java Files> dir
Volume in drive C has no label.
Volume Serial Number is 2EB8-82AA
Directory of C:\Java Files
08/03/2008 04:45 PM <DIR> .
08/03/2008 04:45 PM <DIR> ..
08/03/2008 11:40 AM 180 NullTest.java
08/03/2008 12:30 PM 144 thisisatest.java
Class names should start with an upper-case letter, and each word part
likewise: ThisIsATest.java
Then I did:
C:\Java Files>javac -d . NullTest.java
which led to :
Directory of C:\Java Files
08/03/2008 04:48 PM <DIR> .
08/03/2008 04:48 PM <DIR> ..
08/03/2008 04:48 PM <DIR> forpackagetest
08/03/2008 11:40 AM 180 NullTest.java
08/03/2008 12:30 PM 144 thisisatest.java
And
Directory of C:\Java Files\forpackagetest
08/03/2008 04:48 PM 200 abc.class
08/03/2008 04:48 PM 200 def.class
08/03/2008 04:48 PM 292 NullTest.class
Now this gives error:
C:\Java Files>javac thisisatest.java
thisisatest.java:7: cannot access NullTest
bad class file: .\NullTest.java
file does not contain class NullTest
Please remove or make sure it appears in the correct subdirectory of
the classpath.
The error message even told you so!
NullTest var = new NullTest();
^
1 error
Once again, you have a classpath problem. Classes in a package must be in the
corresponding subdirectory. You put NullTest.class *not* in the subdirectory
'forpackagetest'.
Put NullTest.java in a subdirectory corresponding to the package name:
forpackagetest/NullTest.java
Compile the relative path
javac -d . forpackagetest/NullTest.java
or
javac forpackagetest/NullTest.java
This will put NullTest.class in forpackagetest/.
Step 2 is to compile the other class. It needs NullTest.class (*not*
NullTest.java) in its classpath, because the other class needs that in its
classpath.
javac ThisIsATest.java
Actually, ThisIsATest should go in a package also.
javac forpackagetest/ThisIsATest.java
(with the appropriate 'package' directive in the source).
Either way, because NullTest.class is now in forpackagetest/, it will be found
in the classpath.
Read:
<http://java.sun.com/docs/books/tutorial/java/package/index.html>
<http://java.sun.com/javase/6/docs/technotes/guides/javac/index.html>
--
Lew