I have several files kept in a package, customQ
. This package is imported into a test client called QWithExceptions
. The source tree is arranged as follows:
/tryThis09_01/+
|
-QWithExceptions.java
|
/customQ/+
|
-circularQ.java
-staticQ.java
-emptyQException.java
-fullQException.java
The test client compiles without error when I cd
to tryThis09_01/
and run $javac QWithExceptions.java
.
However, when I decided to experiment a little I find that my intuition regarding packages and their structure is completely off. The actual package customQ
and the test client QWithExceptions
is buried more deeply in a source tree like so:
~/learningJava/beginnersGuide/chapter09/tryThis09_01/+
|
-QWithExceptions.java
|
/customQ/+
|
-circularQ.java
-staticQ.java
-emptyQException.java
-fullQException.java
The linter in my development environment suggested that I change the package declaration in customQ/*.java
from package customQ;
to package beginnersGuide.chapter09.tryThis09_01.customQ;
. After doing so, I then changed the import statement in the test client to reflect the new package name and moved QWithExceptions.java
to ~/learningJava/
and executed $javac QWithExceptions.java
, which resulted in a flurry of compilation errors.
I've also tried $javac -cp .:$CLASSPATH QWithExcpetions.java
and $javac -d . -cp .:$CLASSPATH QWithExcpetions.java
, as well as moving QWithExceptions.java
further up and further down the source tree one directory at a time, all with various errors.
At the moment, I'm grappling with a bad class file
error. While I understand that the compiler wants me to move the offending file somewhere else in the file tree (or perhaps modify the package declarations or import statements) I'm not sure how to do this without invoking a package does not exist
error.
I'm surely missing some essential rule of package writing that isn't (to me) immediately obvious from the trivial implementations found on the broader web or in my Java texts. If you know what it is, please share your wisdom.
I cannot reproduce your issue because you forgot to show the error messages and file content. But I can show you how it works:
My folder structure:
stefan@stefanpc:~/learningjava$ tree
.
├── beginnersGuide
│ └── chapter09
│ └── tryThis09_01
│ └── customQ
│ └── Test.java
└── Main.java
File Test.java:
package beginnersGuide.chapter09.tryThis09_01.customQ;
public class Test
{
public int i;
}
File Main.java:
import beginnersGuide.chapter09.tryThis09_01.customQ.Test;
public class Main {
Test test;
public static void main(String[] args){
System.out.println("Hello");
}
}
Compile:
stefan@stefanpc:~/learningjava$ javac Main.java
stefan@stefanpc:~/learningjava$
Classes and the related filenames should start with an uppercase character. But I assume that this is not your problem cause.
Recommendations of Oracle: https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html