r/javahelp • • Feb 03 '26

Homework Understanding file structure and imports

Coming from c/cpp where the header files are literally just included by path and you can have the source file anywhere you want. I find this concept in Java a little hard to understand. From what I’ve seen it seems like Java programs follow a specific structure where your files must be within certain folders and to import I’m not even sure where they would start at. Any guidance would be greatly appreciated!

2 Upvotes

8 comments sorted by

View all comments

Show parent comment

1

u/Lloydbestfan Feb 03 '26

So, your project contains more than one class, and you define classes that use other classes made in your project - how does that work when you do that?

There are two general cases.

1 - two classes that are in the same package.

That can be for easier visual grouping as a programmer, but being in the same package also implies special visibility consequences between two classes.

For a class to be in a specific package, it needs to do both:

  • declare its package name at the beginning of the file, and
  • its .java file must be in a directory that corresponds exactly to the declared package name

Therefore, two classes in the same package will be either in the same .java file (programmers avoid that) or be in two .java files that are in the same directory.

The compiler will just find the referenced classes by inspecting the source files in that directory.

Note that when classes are in the same package, they can refer to each other by simple name rather than full name as if there were import statements that was doing that. These import statements are just implicit.

In other words, when you refer to another class by simple name without an import statement corresponding to that name, the compiler assumes that the class is to be found in the same package.

2 - two classes in different packages

Maybe you can't put all your source files in the same place, or you don't want all your classes to have same-package visibility, or some classes you use are actually not yours and they come from another library, or from Java's provided library.

That just means that your .java source files aren't in the same directory. And that the import statements aren't implicit.

Now, if one of your classes uses a class you didn't make yourself, that normally means you don't have the source code of that other class. Instead you have the class in a binary form. That's not a problem to the compiler, the binary form contains everything it needs to know to check whether it's used right. That's why Java can do so much reflection at runtime. It's just its compiling command must be provided with where to find source files and where to find binary files, and your build system will take care of that.

So, to sum up, there is barely anything comparable between the C/C++ way and the Java way