What is the purpose of defining a package in a Java file?

JavaPackage

Java Problem Overview


I am a newbie and just learned that if I define say

package my.first.group.here;
...

then the Java files that are in this package will be placed under my/first/group/here directory.

What is the main purpose of putting some Java files in a package? Also, if I choose to adopt this, how should I group them?

Thank you


EDIT: For anyone who might have the same question again, I just found this tutorial on packages from Sun.

Java Solutions


Solution 1 - Java

Let's start with the definition of a "Java package", as described in the Wikipedia article:

> A Java package is a mechanism for > organizing Java classes into > namespaces similar to the modules of > Modula. Java packages can be stored in > compressed files called JAR files, > allowing classes to download faster as > a group rather than one at a time. > Programmers also typically use > packages to organize classes belonging > to the same category or providing > similar functionality.

So based on that, packages in Java are simply a mechanism used to organize classes and prevent class name collisions. You can name them anything you wish, but Sun has published some naming conventions that you should use when naming packages:

> Packages > > The prefix of a unique package name is > always written in all-lowercase ASCII > letters and should be one of the > top-level domain names, currently com, > edu, gov, mil, net, org, or one of the > English two-letter codes identifying > countries as specified in ISO Standard > 3166, 1981. > > Subsequent components of the package > name vary according to an > organization's own internal naming > conventions. Such conventions might > specify that certain directory name > components be division, department, > project, machine, or login names. > > Examples: > > * com.sun.eng > > * com.apple.quicktime.v2 > > * edu.cmu.cs.bovik.cheese

Solution 2 - Java

I a large application, you are bound to have two files named exactly the same (java.util.Date and java.sql.Date), especially when you start bringing in third party jars. So basically, you can use packages to ensure uniqueness.

Most importantly, in my opinion, packaging breaks down projects into meaningful segments. So my SQL package has sql-related code, and my logger package handles logging.

Solution 3 - Java

In addition to the namespacing mentioned in other answers, you can limit access to methods and fields based on the scope declared on that member. Members with the public scope are freely accessible, to limit access you normally define them as private (i.e. hidden outside the class). You can also use the protected scope to limit access to the type and its children. There is also the default scope (a member with no qualifier has the default scope) which allows child types and types in the same package access to the member. This can be an effective way of sharing fields and methods without making them too widely available, and can help with testing.

For example the method below would be visible to all other members of the same package.

public class Foo {
    int doSomething() {
        return 1;
    }
}

To test the method you could define another type in the same package (but probably a different source location), that type would be able to access the method.

public class FooTest {
    @Test
    int testDoSomething() {
        Foo foo = new Foo();
        assertEquals(1, foo.doSomething());
    }
}

Solution 4 - Java

It allows the program to be composed from multiple different programs/components/libraries, so that their class names will not conflict and the components are easier to organize. See http://java.sun.com/docs/books/tutorial/java/package/index.html

In Java it's customary to name packages as reverse domain names. For example, if your company's domain is "initech.com" and you are making a program called "Gizmo", the package names are typically prefixed "com.initech.gizmo", with subpackages for different components of the program.

Solution 5 - Java

Packages are important for giving flexibility of classes separation. They can be used for:

  • separating projects
  • separating modules
  • separating application layers (business, web, dao)
  • further finer grained code separation

For example

com.mycompany.thisproject.thismodule.web

Could indicate the web layer of some module.

Solution 6 - Java

Ultimately, there are 3 core reasons we want to use packages in Java.

  1. Easier Maintenance

Organizing classes into packages follows the separation of concerns principle by encapsulation and allows for better cohesion in the overall system design. Moving further, packaging-by-feature allows teams of developers to find relevant classes and interfaces for making changes, supporting vertical-slicing techniques for scaled approaches used in agile methodology. For more information, see blog post: Package your classes by Feature and not by Layers and [Coding: Packaging by vertical slice][2].

  1. Provide Package security

Packages allow external access to only public access modifiers on methods in contained classes. Using the protected or no modifier will only be accessible to classes within the same package. For more information, see post: https://stackoverflow.com/questions/21133124/which-java-access-modifier-allows-a-member-to-be-accessed-only-by-the-subclasses

  1. Avoid similar naming

Similar to the namespaces of .NET, class names are contained within the scope of their containing package. This means that two mutually exclusive packages can contain classes with the same name. This is because the packages themselves have different names and therefore, the fully qualified names are different. For more information, see tutorial [Naming a Package: The Java Tutorials][3].

[2]: https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html "Naming Packages"

Solution 7 - Java

From the Wikipedia page on the topic:

"A Java package is a mechanism for organizing Java classes into namespaces similar to the modules of Modula. Java packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather than one at a time. Programmers also typically use packages to organize classes belonging to the same category or providing similar functionality."

Solution 8 - Java

> also, if i choose to adopt this, how > should i group them?

This depends largely on the design pattern(s) you will employ in your project. For the most part (particularly, if you're quite new) you'll want to group them by functionality or some other logical similarity.

Solution 9 - Java

Java is very exact in its implementation. It doesn't really leave room for fudging.

If everyone were to use the same package, they would have to find some "World Wide" way to ensure that no two class names ever collided.

This lets every single class ever written fit into its own "Place" that you don't have to look at if you don't want to.

You may have different "Point" objects defined in 4 different places on your system, but your class will only use the one you expect (because you import that one).

The way they ensure that everyone has their own space is to use your reverse domain, so mine is "tv.kress.bill". I own that domain--Actually I share it with my brother "tv.kress.doug" and even though we share the same domain, we can't have a collision.

If a hundred divisions in your company each develop in Java, they can do so without collision and knowing exactly how to divide it.

Systems that don't do this kind of division seem really flaky to me now. I might use them to hack together a script for something personal, but I'd feel uncomfortable developing anything big without some strict packaging going on.

Solution 10 - Java

Other people have provided very Java-specific answers which are fine, but here's an analogy: why do you organize files into directories on your hard drive? Why not just have a flat file system with everything in one directory?

The answer, of course, is that packages provide organization. The part of the program that interfaces with the database is different than the part of the program that displays a UI to the user, so they'll be in different packages.

Like directories, it also provides a way to solve name conflicts. You can have a temp.txt in a couple different directories in the same way that you could have two classes that appear in different packages. This becomes important (1) when you start combining code with other people out there on the internet or (2) even realize how Java's classloading works.

Solution 11 - Java

Another important thing about packages is the protected member for access control.

Protected is somewhere between public (everyone can access) and private (only class internal can access). Things marked as protected can be accessed from within the same package or from subclasses. This means that for limited access you don't have to put everything in the same class.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionderrdjiView Question on Stackoverflow
Solution 1 - JavaWilliam BrendelView Answer on Stackoverflow
Solution 2 - Javageowa4View Answer on Stackoverflow
Solution 3 - JavaRich SellerView Answer on Stackoverflow
Solution 4 - JavaEsko LuontolaView Answer on Stackoverflow
Solution 5 - JavaMercer TraiesteView Answer on Stackoverflow
Solution 6 - JavanewmanicspreeView Answer on Stackoverflow
Solution 7 - JavaPaul SonierView Answer on Stackoverflow
Solution 8 - JavaYohnnyView Answer on Stackoverflow
Solution 9 - JavaBill KView Answer on Stackoverflow
Solution 10 - JavaView Answer on Stackoverflow
Solution 11 - JavaTamarView Answer on Stackoverflow