At least on my machine when I put 2 Java class files on the same folder, without making them part of the same package, they already see one another, so from one file I can call a public class from the other file and vice-versa.
Questions:
Is this the general case or a coincidence that may not work on every platform?
If this is not a coincidence, I am guessing the purpose of packages is to allow you to organize your class files and make they share stuff, even if they are spread across different folders and paths. Is this correct or I am missing something?
If no package name is specified, the classes in the file go into a special unnamed package. And this is the same case for all files with no explicit package specification. Hence, they all fall into the special unnamed package, and exhibit the behavior that you are seeing.
You might want to go through this for a better understanding.
If they're in the same directory then they're in the same package, or are you copying .class files around after they've been written by the compiler?
Packages are a way of organising classes into a namespace. There are plenty of reasons to do this, the best bet is to start with the tutorial.
I sure it is general case, but it is bad approach.
You are right, but more general reason to use package is to separate namespaces, for example, you have to create Car class, but there are many people who want to use this classname, thats why you have to use package, for example: com.yourcompany.yourproject. In such case you can use your Car class from your package without implicitly defining package and you also can use other Car classes in such manner: new com.google.general.Car();
In the java rules, it is recommend to use domain name right-to-left for providing unique package name.
Related
I want to understand the packing methodology in real big projects.
Suppose we have a package com.abc.xyz, and for this, we really have a path like com/abc/xyz.
Is it possible to have multiple same package names in different directory structure like:
Directory path 1:
/home/user1/project/module1/src/java/com/abc/xyz
Directory path 2:
/home/user1/project/module2/src/java/com/abc/xyz
And finally when we create jar for the whole project, do we create jar with respect to com directory?
When some application uses import com.abc.xyz, how does it know which directory path's package it is referring to?
And finally, is there any good book/resource which gives guidelines about packaging, how to divide project into modules, package names etc.
One more thing, does a project have common package base name like in above case:
com.abc.xyz (e.g., org.apache.hadoop ).
Thanks,
Vipin
Packages created in different source directories are the same package, as far as the classloader is concerned. It also doesn't matter if the class files are in the same jar or different jars. The JVM does not discriminate based on where the source code came from.
(Of course if you have two jars loaded by different classloaders those are going to be treated differently.)
One case where you frequently have different source trees with the same package is when you have tests in a different directory (using the usual Maven convention where the code is under src/main/java and the tests are in src/test/java) but with the same package as the code that they exercise. These tests are able to exercise protected and package-private parts of the code under test, because they're in the same package as that code.
The path of directories inside the jar should start at the root of the package. (The topmost directory should be /, then one called com or org or whatever, etc.) Packages do form a tree-like structure, and when you put your code in a filesystem you end up having a hierarchy of packages, but the language itself doesn't recognize a concept of "subpackage" (except that packages that start with java are special and get special treatment by the classloader).
Organizing code into packages is done differently by different people. Some people like to organize their code by layer (putting all controllers in one package, all services in another package, all daos in still another package), some like to organize their code by feature.
Package-by-layer is the conventional way of organizing code, it seems to be the preferred practice in the Java community. One consequence of this is that when code implements a feature as a vertical slice at right angles to the package structure (as it may require a new controller endpoint, maybe a new service method, etc.), so closely-related bits of code for the same feature end up scattered across different directories. The Java Practices website makes an interesting case for package-by-feature:
Package By Feature Package-by-feature uses packages to reflect
the feature set. It tries to place all items related to a single
feature (and only that feature) into a single directory/package. This
results in packages with high cohesion and high modularity, and with
minimal coupling between packages. Items that work closely together
are placed next to each other. They aren't spread out all over the
application. It's also interesting to note that, in some cases,
deleting a feature can reduce to a single operation - deleting a
directory. (Deletion operations might be thought of as a good test for
maximum modularity: an item has maximum modularity only if it can be
deleted in a single operation.)
Here's an SO question asking about package by feature or layer.
Yes, you could make duplicate packages in separate directories, but I can't think of a good reason to do it. If the classes within the package have the same names you can certainly get namespace collisions. I am not sure what "module" means in this context but I'd recommend
com.abc.module1.xyz
com.abc.module2.xyz
instead. Those would be distinct packages to the classloader. You can still keep your /home/user1/project/module1/ directory structure up front, that doesn't matter.
From 2 modules you will have two seperate jar files: module1.jar and module2.jar. Both will be loaded into ClassLoader when application starts.
When some application uses import com.abc.xyz, how does it know which directory path's package it is referring to?
Classloader will handle that. http://www.javaworld.com/article/2077260/learn-java/the-basics-of-java-class-loaders.html
If you trying to develop multi module application i recommend you to check Maven tool:
http://maven.apache.org/
Why maven? What are the benefits?
For guidance for package organization you can just google 'java packages' phrase.
http://www.tutorialspoint.com/java/java_packages.htm
https://www.facebook.com/Niranthara-Jaya-JavaSocial-Media-Apps-Software-Project-Management-244119296136021/
This page is for people who wish to know how to work with real world Java projects. Send a message to this page and check out the articles.
Since I have many separate classes for my program I created 2 folders (I'm using JDeveloper) in my project called "panels" and "buttons" where I've placed the corresponding classes that extend JPanel or JButton. I've used the same package for all my classes so that those that are placed in a folder can be referenced by the rest of the classes that are not placed in the same folder without importing (all my classes belong to the same package, e.g. mypackage).
My question is should I change this and make the classes of a directory belong to a separate package (e.g. classes in "panels" directory to belong to the mypackage.panels package and classes in "buttons" dir to belong to mypackage.buttons)? The first way works fine and has the benefit of lacking the need to import but I was wondering if this is the "correct" way to do this...
Yes, in general I'd strongly encourage you to make your directory structure match your package structure. Some IDEs will enforce this, and other developers are likely to expect it - it's useful to know exactly where to find a particular file.
Now whether you really want separate packages for these controls is a different question, and one we can't answer.
Every time I look at some Java source code, I find myself surfing in a folder that has folder that has folder that has folder in it etc. Why does Java require so many nested folders, which have nothing else in them except the new subfolder?
For example:
https://github.com/halfninja/android-dragcontrol3d/tree/master/src/uk/co/halfninja/android
That's probably not the worst example, but there are two folders "uk" and "co" that just don't make sense. I see this in Java sources only!
And for example minicraft: http://www.ludumdare.com/compo/ludum-dare-22/?action=preview&uid=398
import com.mojang.ld22.gfx.Font;
import com.mojang.ld22.gfx.Screen;
import com.mojang.ld22.gfx.SpriteSheet;
Why not just write:
import gfx.Font;
import gfx.Screen;
import gfx.SpriteSheet;
That's so much cleaner.
(I have never programmed in Java.)
These are there to prevent conflicts with other jars. Having something like the company url in the package name makes it likely to be unique enough to not conflict with someone else's package and classes.
Your example is a good one, since it seems pretty reasonable to imagine two people thinking of using "gfx" as a package name and with classes like Font or Sprite. Now, if you wanted to use both of them, how could you since the package and class name would be the name?
Your way is cleaner, but it assumes nobody else in the world is ever going to create a package called gfx, which is a pretty weak assumption. By prepending your reversed domain name, you create a unique namespace that avoids collisions.
This fits perfectly with the "culture of sharing" that pervades Java programming, in which applications typically combine large libraries from many sources.
In Java, the convention is to name your packages (which correspond to the folder structure containing your code) with information identifying your organization (typically including a TLD and the company name) and project (which might add a few more sections).
Being more specific like this also reduces the likelihood of namespaces accidentally colliding with eachother.
It's merely an organizational technique for preventing namespace conflicts. Nothing more or less. Java package names match the underlying directory structure, so any organizational pattern at the package level will be reflected there. It's typical for teams to start their package names with their organization's name and wax specific. This is simply convention, but it's ingrained and should be followed absent a very good reason.
It's all about Namespaces. With 'Namespaces', you can create 2 classes with the same name, located in different packages/folders. This Namespace logic can also be used for creating 'Access Privileges', etc etc. Below are some links:
1) Namespace
2) Java Package
3) Java Package Naming Conventions
EDIT: Let us assume that you are creating a new project and are using 2 open source frameworks from companies/organizations - comA and comB. Also, let us assume that comA and comB have created a class in their projects with the same classname. Now, with the Java package naming conventions, we have com.comA.SomeClass and com.comB.SomeClass. You can import and use both the classes in your class, without having a conflict. This is just a simple example. There are other uses from this naming convention.
If you want to share code with everyone else, but use generic names without conflict. its considered good practice to include you domain name (backwards)
Everyone write a package called gfx.Font you wouldn't be able to use more than one version in the same application.
You might feel your code will not be shared with the world (or even should not be shared) In which case, a shorted package structure may be simpler.
If you use an IDE, it does a good job of hiding long package structures so you don't need to worry about it.
This is due to recommended packaging structure. In large projects, so many packages/libraries are used and in order not to put source files into same folder with another library, programmers put their source codes into unique folders. As websites are unique, it is a convention to use packaging structure that looks like folder structure of websites.
Java does not require anything: you can just put all your classes in the default package and surf away. But for serious projects that kind of organization is not only wise, it's mandatory. The com.mojang.ld22 part is just a convention:
com = either this or org, java/javax for official packages
mojang = second part is company name
ld22 = third part is application name
In Java, there is what is called package. Does library in C++ represent the same meaning, especially in terms for example of containg relative classes and the use of protected members?
Thanks.
There are different dimensions of what a package means in Java. As a container that differentiates the names of the classes inside from the names of classes in other packages, its equivalent would be c++ namespaces.
As a unit that guarantees access to non-private members to classes in the same block, there is no equivalent in C++. The access level granted to a class is independent of the namespace where the class is defined.
As a way of ordering your sources in the disk, there is no equivalent, the C++ language has no requirements on how the code is stored in files.
Regarding c++ libraries, that is closer to jar files in Java. They bundle different classes that share some relation. A jar can contain more than one package, and more than one jar can contain classes from the same package. Similarly with libraries, they can contain classes from different namespaces and/or different libraries can contain classes from the same namespace.
The closest to Java packages are namespaces in C++.
They can be nested into one another, and you need to specifically declare that you are using them or a part of their contents. However, they do not enforce any physical file hierarchy like Java packages do.
Strictly speaking I think that namespaces in C++ provide the same semantics.
I guess it is more related to namespaces in C++.
Java and C++ both use libraries. Library can be any independent set of classes[probably a framework] which can be accessed in our code.
External Libraries are there in both Java and C++. Just the formats vary, .jar in Java and .dll/.so in C++.
Purpose of Packages and Namespaces are different from Libraries. They avoid running out of names by allowing user to logically group the source.
A package in Java is a namespace for classes, interfaces and enums. Package name, a dot and the classname form the fully qualified classname of a class:
com.example.hello.HelloWorldApplication
^--packagename--^ ^-----classname-----^
The dots in the package name have a different meaning then the dot between the names: the first two dots of this example are part of the package name, the last one is a separator.
This should be kept in mind, because there's a common misunderstanding regarding package names: just because the names can be mapped to a hierarchical folder structure, some people think, package names have a hierarchy too - which is not the case: hello is not a "subpackage" of example!
But, to create a simple mapping to folders and files, a classloader can simply take the fully qualified class name, replace all dots with a slash and append .class to get a relative path to a class file.
But note again, that a folder/file mapping is not required t load classes - we can invent a class loader that gets classes from a database or a remote service - a folder/file mapping wouldn't make any sense in that case.
How can I export a jar without some class or package which I don't want others to use,but which is needed in project,means I can't delete them.
This doesn't make a lot of sense.
If the classes are needed to compile the project, then there are likely to be static dependencies on them in other classes. (Otherwise ... you would be able to just delete it / them.)
But if there are static dependencies on those classes, then you won't be able to run the applications unless those classes are present in the JAR file. If you leave the classes out of the JAR to stop people using them (or whatever), your application will die on startup with "class not found" exceptions.
If you want to stop people using the classes directly, you could try the following:
Change the classes access to "package private". This doesn't make it impossible to use them, but it makes it more difficult.
Change your project so that the dependencies on the classes are entirely dynamic; e.g. via Class.forName(...) or dependency injection. Then you can exclude the classes from the JAR as required. But once again, if your application needs to use the classes, they have to be accessible at runtime (somehow), and it will therefore be possible (somehow) for other people to get hold of them.
Change your project to allow you remove the classes entirely. This is the only sure-fire solution.
Finally, before you go to all of this trouble you should ask yourself why you are even bothering to do this. Why don't you just let people use the classes anyway? What is to stop them getting the classes from somewhere else ... or implementing their own versions from scratch?
If the class is needed for your program to work, you can't omit it from the JAR.
You can put classes in a package that has something like "internal" in its name — e.g. com.example.internal — to indicate that the classes aren't meant for others to use or rely on. It can't prevent anyone from using your class for their own purposes, but it at least indicates that they do so at their own risk, that your internal interfaces might change in future versions of the program, etc.
A simple way is to use the package private access modifier for classes. That will make it difficult for others to access the classes, but it will also affect your ability to use them from other packages.
A more advanced way would be to use OSGi and only publish those classes you want others to use. That will make it impossible for others to access the classes while not restricting your access to them.
Put them into a separate jar file, include that jar file (as a single file, maybe with a nondescript name) into your jar file, create a custom class loader to open that embedded jar file from your code, bootstrap an entry point with reflection (because you cannot have static dependencies on it) into that new class loader .
Or just accept the fact that since the code is in there somewhere, any amount of obfuscation is just an inconvenience to everyone and cannot really hide anything.