简体   繁体   中英

Java cannot import from child of parent directory

OK so I am making a Java Programme and I have the following directory setup: - MyProgramme
|__ Engine
|______ utils
|__________ Important.java
|
|__ src
|______ main
|__________ MainApp.java

Inside MainApp.java I have an import statement:

import Engine.utils.Important;

I have also tried

import utils.Important;

To no avail. Is there something stupid I am missing? Why cant I import Important from MainApp?

I am running Windows 10, cmd java -version returns the following:

java version "1.8.0_111"
Java(TM) SE Runtime Environment (build 1.8.0_111-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.111-b14, mixed mode)

Thanks

Quick Edit: Have also tried MyProgramme.Engine.utils.Important; Second Edit: The error I am getting is java: package Engine does not exist

As you are only a starter, move utils folder to src. Then use it as import utils.Smth; and you should be fine.

Also consider using some development editors. Such as IntelliJ, Eclipse or NetBeans. Import the project and you will be fine :) Manually playing around with the classpath is not a good idea for you.

You may want modularity in your project right now, but you don't know how to use packages well. Read up on that.

If you already know all that stuff, you should read about gradle or maven. In a nutshell these tools combine several projects into one. But in an early stage of a project this would be a major overengineering and cause a large overhead of development.

Provided your classpath is set up correctly, your first one ( import Engine.utils.Important; ) is fine. You need to ensure the classpath includes the parent of your Engine directory, and the parent of your main directory (assuming your Main class is in the package main , not src.main , which would be odd).

*nix example:

If the top level of your hierarchy is ~/temp , then make sure your classpath includes ~/temp and ~/temp/src . For instance, this works fine:

javac -cp ~/temp:~/temp/src src/main/Main.java

Windows example:

Or on Windows, if you assume your base directory is C:\\Temp , then:

javac -cp C:\temp;C:\temp\src src\main\Main.java

Assumptions

The above assumes Important.java has

package Engine.utils;

and that Main.java has

package main;

Side note: The overwhelming convention in Java is that package names are in all lowercase. So engine rather than Engine .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM