1

I have class Foo, its first line reads package com.bar.something.baz. Its file is in /com/bar/something/baz/.

Why do I have to declare the package in the class file and then put the file in the same path as the package I declared? Isn't it redundant? Couldn't the compiler infer it from the path?

  • 4
    The compiler could feasibly infer it from the path, if it knew which directory was the top level. You say that your file is in com/bar/something/baz, but as far as the compiler knows, it's also in bar/something/baz, something/baz, baz, and fishcake/com/bar/something/baz – Pete May 30 '17 at 15:54
  • 2
    There are Java implementations which don't use files. – Jörg W Mittag May 30 '17 at 22:14
2

When it was created, the Java compiler did not require a particular directory layout in order to work correctly. It's a design that's really nice for small projects, because I can have a handful of source files in a single directory, and each one can have whatever package declaration it needs. It gives the programmer a lot of control over where files are placed, but along with the extra control comes the cost of doing the work to organize things manually. It's not a design that scales well, however, which is why for any organized tree of source code the package declaration really looks like it's redundant. One good reason to use an IDE is to avoid the manual effort of managing your source files, which can be quite tedious.

The only environment I know of that lets you organize your code without these types of redundant hierarchy specifiers is Smalltalk. Most Smalltalk systems work with a live image, so you don't have a bunch of individual source files to manipulate. Instead, you directly manipulate classes and methods. The idea of manually manipulating thousands of source files is foreign to Smalltalk systems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.