Help with Packages in Java - Import Does Not Work

Error importing package in Java

I have found the problem.

It appears that Dr.Java ignores complitely the CLASSPATH variable. It is necessary to set in preferences where are the .class files.

Import cannot be resolved in java

In your image you have the class ClassA not A.

So the error is:

 "import com.test.foo.A cannot be resolved"

You should import the class ClassA.

package com.test.foo1

import com.test.foo.ClassA;

public final class B {

private method2(){

//...... some code....
ClassA.method1();
}
}

Can't import a sub package in java

Most likely, you are not compiling Pixel.java from the root directory of the project, and you compile it from within the directory where that file is located (image/). In this case, directory structure matching your package declaration image/color is not available from image/, as you do not have image/image/color.

Package declarations must match the directory structure they are declared in, relatively to the root directory, as they are looked up relatively to the project's root directory. E.g. if you are compiling A.java, which has a dependency B.java (A imports B) defined under the package a.b;, then the B.java will be looked up in the corresponding a/b/ folder, and if you are in the folder, from where, a/b/ is not available, compiler will complain, that it cannot find the package/directory a/b/.

You have two ways to solve this when using javac:

  • Best is to compile your file(s) from the root directory. This way, all the package declarations will match the directory structure (assuming your package names are correct and they match directory names) relatively from your root directory;
  • You can use -cp flag, to tell to the Java compiler where to look for other sources, in case you are not compiling your file(s) from the root directory of your project. Note, that here, as well, you should provide a path of the root directory of your project, as the class(es) package(s) will only match the folder structure, when looked up from the root directory of the project.


Related Topics



Leave a reply



Submit