Search code examples
javaclasspackagejavac

Java not compiling .class files under $CLASSPATH


I'm trying to figure out how organize source and class files working with packages. I found a very useful tutorial. But I still have some questions.

As far as I understood it is a good practice to have an isomorphism between name of packages and name of the directories where elements of a package are stored. For example if I have a package named aaa.bbb.ccc which contains class ddd it is a good practice to have a class file called "ddd.class" and located in "$CLASSPATH/aaa/bbb/ccc/". Did I get it right?

If it is the case, will Java compiler put *.class files into the correct directory automatically?

I was not able to get this behavior. I set the $CLASSPATH variable to "/home/myname/java/classes". I executed javac KeyEventDemo.java which contains package events;. I expected that javac will create a subdirectory events under /home/myname/java/classes and put the KeyEventDemo.class in this subdirectory.

It did not happen. I tried to help to javac and created "events" subdirectory by myself. I used javac again but it does not want to put class files under "/home/myname/java/classes/events". What am I doing wrong?


Solution

  • You need to use the -d option to specify where you want the .class files to end up. Just specify the base directory; javac will create any directories necessary to correspond to the right package.

    Example (based on your question):

    javac -d ~/java/classes KeyEventDemo.java