-
Why in the files that are in a Java package I should write the "package" thing in it? It’s not indirectly assumed that if it’s in the directory, then it’s in the package?
-
I come from the C++ world. I always imported the .h of the classes which I need from other files that use that class (I mean, I want only to "show" the header, not the implementation). But now I’m a bit confused about the imports in Java. How is this done in Java?
Why in the files that are in a Java package I should write the
Share
No, that is not assumed. After all, what’s my package called? com.mypackage.stuff? src.com.mypackage.stuff? myproject.com.mypackage.stuff? C.Users.makakko.workspace.myproject.src.com.mypackage.stuff?
If you only base the package off of the folders, is it relative to the drive root? What if the project is developed on a different drive letter on a different machine? Is it relative to the location of javac.exe? Again, what about different install directories? What about the working directory when running javac? But you can specify a location for javac to find your sourcefiles in. What if you want to do a simple test program, or teach someone Java who has never programmed before; do you have to use/explain the whole concept of package structure?
If you omit the
packagespecifier, then you’re still in a package. It’s just the “default package”, which has no name.Header files are more of an artifact from the way C needs to be compiled than a way to achieve information hiding. In C, a method must be defined before it can be referenced. If you want to have several methods which refer to one another, you have to define all of them before using any of them, hence the header. The headers in C++ carry over from that, but changes in C++ alter the necessity of headers.
In Java, the compiler will look at all of your method and class signatures before doing anything which required the method/class. The function served by headers is put into the compiler itself. You can’t depend on the header for your information hiding, because
Code can be placed within a header file
Unless you use real information hiding such as a separate library, a programmer can go find the c/cpp file that matches the header without issue
Similarly in Java, you can only get real information hiding by removing the source. Once you’ve made the source inaccessible, you expose the API with public/protected classes, enums, and interfaces. For bonus points, write explanatory JavaDoc comments for everything, and run javadoc.exe over your source to produce separate documentation for anyone who will use your package(s).