cannot access class in the same package without adding to classpath

Project structure:

./src/com/example/Test.java
./src/com/example/Dog.java

Test.java

package com.example;

public class Test {
    public void testing() {
        Dog d = new Dog("Lab");
    }

}

Dog.java

package com.example;

public class Dog {
    private String breed;

    Dog(String breed) {
        this.breed = breed;
    }
}

It compiles successfully when I try this

.\src > javac com\example\Test.java

But it fails when I do this

.\src > javac -cp "C:\Tomcat\lib\servlet-api.jar" com\example\Test.java

With this error

error: cannot find symbol
                Dog d = new Dog("Lab");
                ^
  symbol:   class Dog
  location: class Test

I'm guessing it's because the existing classpath is overwritten. How do I avoid that?

Also, can you explain more on detail why it fails when it is run from the parent directory of \src, like this

javac src\com\example\Test.java

I get the same error as the one with classpath.

Sorry for all the confusion.

Thank you Jon Skeet for helping out.

Jon Skeet
people
quotationmark

The compiler will treat directories on the classpath as source root directories - in other words, when trying to find classes for package com.example, it will look for both class and source files in a com/example subdirectory from each directory on the classpath.

When you compile like this:

.\src > javac com\example\Test.java

... the classpath is implicitly "the current directory".

When you specify the classpath explicitly like this:

.\src > javac -cp "C:\Tomcat\lib\servlet-api.jar" com\example\Test.java

... it isn't. You'd need to add . to the classpath explicitly:

.\src > javac -cp "C:\Tomcat\lib\servlet-api.jar";. com\example\Test.java

Similarly when you're not in src, you'd have to specify src as being on the classpath:

. > javac -cp src src\com\example\Test.java

Personally I try to make sure that all the sources I want to compile are explicitly listed in javac anyway - otherwise it's quite possible to use out-of-date class files rather than recompiling the source code.

people

See more on this question at Stackoverflow