This question already has answers here:
What is the purpose of defining a package in a Java file? [closed]
(11 answers)
Closed 7 years ago.
Why do we use packages in Java?
How to use them?
Packages are mostly just a way of organizing code. The JDK has thousands of classes in, and a large application has thousands more. Why would you not want to organize those into some sort of hierarchy allowing you to find the classes you're interested in easily?
Packages also participate in access control in Java (but not in .NET, interestingly) - but I'd say the main purpose is to help humans organize their code meaningfully.
It also means that occasionally you may want or need the same class name in multiple packages - where the package name effectively provides the context. Now if you're working in a single codebase for a single application, that's usually something to try to avoid - but if you've got a large codebase where many different applications use many different parts of it, that may be better than trying to have a unique name for every single class. (A typical example of this is in user interface code - just looking in the .NET libraries, there's a "Button" class in three separate namespaces, for three separate UI frameworks.)
Think of packages in java as the folders on your PC. You like to keep different types of files in different folders, just as the same you keep different types of classes and interfaces in different packages in java.
By doing so, we get some advantages and some of them are listed below-
Grouping similar files: You keep videos in a folder like Entertainment\Videos, documents in a folder like Personal\Documents. Like this similar kind of classes and interfaces are kept in same packages in java.
Security: Just as you can hide or set a password to protect the contents of your files in a folder you can achieve same kind of feature by declaring your class members as protected or without any access specifiers.
Readability and Accessibility: Suppose need to find a kind of class or interface, then you can find that kind of package by its name and proceed your search. Thus you can narrow down your search area and then find and access it in an easy way.
Usage of only required files Suppose you're just executing a simple hello world program and you don't need so many classes to be imported, in such a case all the classes available in java library will not be imported. If you don't have packages then each and every class in java library will be imported.
We define Class/ Interface in package with a java keyword package followed by the package structure. It must be the first statement of your Class/ Interface. If you don't define a package name then that file will be placed in a default package, which is your source code folder.
package com.my.package.MyClass;
Packages are used in java preceded by a keyword import. Levels of packages are accessed with the dot (.) operator as we do '/' or '\' in case folders on the PC.
Import a class MyClass available in a package named com\my\package:
import com.my.package.MyClass;
Import all the classes available in a package named com\my\package:
import com.my.package.*;
Import only a static field of a class, so that you can directly access it without class name:
import static com.my.package.MyClass.myStaticField;
Packages are a way to group similar classes. You do not want to put all your classes in one package, do you?
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
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.
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
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.
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());
}
}
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.
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.
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) 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:
Which Java access modifier allows a member to be accessed only by the subclasses in other package?
3) 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].
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."
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.
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.
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.
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.
I want to get into creating applications, however, I do not know when I should use packages. How should packages be used? How do you know what class to put in what package?
Except for really trivial programs that involve not more than one file, you should always use packages. A typical package structure is the following
com.<your_company>.<your_project>.<sub_system>....
or
org.<your_organization>.<your_project>.<sub_system>....
or (if you don't really belong to any organizations or companies)
<some_name>.<your_project>.<sub_system>....
where ... above indicate some more structure within your sub system. And
<some_name> is just some name that won't be easily in conflict with names that are used by other people. Don't worry. Even if you pick a name that
is already used by someone else, you won't be in trouble until the moment you
try to compile two packages of the same name together (obviously that
should not be allowed). So these names are all valid choices for <some_name>
playground
mytest
chapter1
tutorial
By convention, package names are always in lowercase. And in contrast, class names always start with an uppercase character. For example, in
com.google.gwt.core.client.EntryPoint;
the package name is com.google.gwt.core.client, and the classname is EntryPoint
A good way to learn is to see how other projects organize their packages and classes. Below I show some examples (which include both package names and class names):
org.hibernate.annotations.Cache;
org.hibernate.annotations.CacheConcurrencyStrategy;
com.google.gwt.core.shared.GWT;
com.google.gwt.core.client.EntryPoint;
com.google.gwt.user.client.Window;
com.google.gwt.user.client.Window.Location;
com.google.gwt.user.client.rpc.AsyncCallback;
com.google.gwt.user.client.ui.RootPanel;
com.smartgwt.client.util.DateUtil;
com.smartgwt.client.util.SC;
com.smartgwt.client.widgets.Canvas;
com.smartgwt.client.widgets.HTMLFlow;
com.smartgwt.client.widgets.layout.VLayout;
One more observation I would like to make is that package names
are often organized top-down (from big to small). This convention is
the reverse of the
convention of how Internet domain names are formed (from small to big).
In the above example, Google's GWT project has named their package as
com.google.gwt....
while Google's Internet domain names are in this form
....google.com
Many companies and organizations use the reverse of their domain names to form the prefix of their packages.
Use packages to seperate classes in your applications by concerns. This helps you in several ways:
avoid name conflicts between unrelated classes
group related classes together and isolate unrelated classes in different packages
which all should lead to a better maintainability of your application. If you can find reasonable names for your packages, you can get even a clue what purpose the classes in your package have.
You can read more about it in the official java tutorial. A very common use case is to seperate
application logic (also called model) from
presentation / gui code (often called view)
See how Java itself uses packages to seperate things:
java.lang.Math for computations
javax.swing, java.awt for gui frameworks
java.nio for buffered input/output
Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
If your program has a small amount of classes, like 3 classes
you may not have to separate them into packages.
Your classes are separated into packages in a logical way.
for example:
If you have a program that encryptes data, each of the encryption algorithms
can be separated into classes, and all of those encryption classes can be in the same package
I am developing a generic Android game engine that will be used in many of my Android apps as the base system. The problem is that in all of my Java files I currently have to hardcode the package name like this:
package com.example.mygameengine;
But because I want to use the code of my generic game engine in many different apps, I need to find a way to specify the package name for the Java files at compile time because I do not want to keep several copies of my Java sources just because of differences in the package name. I want to have one central source tree and the package name should be dynamically changeable depending on the app I'm about to compile.
So is there a way to do something like this:
package $(PACKAGE_NAME)
In the Java sources where $(PACKAGE_NAME) is to be substituted with the real package name at compile time? Maybe javac has an option that allows me to specify a package name for the file it is passed instead of taking it from the file itself? Note that I'm not using Eclipse but barebones command line tools like ant and make.
EDIT: I do not understand why this is tagged as a duplicate. I've asked a fundamental question about whether the "package" directive in the Java language requires a hard-coded string argument in the source code or whether it is also possible to set this package name at compile time using a compiler directive. That's quite a different question than the one that has been linked here as the presumedly "original" question which is much more closely tied to the Android build system. My question is about the fundamentals of the Java language, not about the Android build system.
Can you build your generic game engine code into a stand alone JAR.
Then you can include it as a dependency into each of your Android app that uses it.
With proper versioning you will then have just one central place where this code is stored.
You can't. And that's not the proper approach to code reuse.
Simply package your commonly used code in a jar and include that jar in every project you want (in Android you do that by adding the class to the classpath, and then marking it as exported in the "Order & Export" tab)
It's not possible, because its part of core meta-data about your class
A package is a collection of related Java entities (such as classes, interfaces, exceptions, errors and enums). Packages are used for:
Resolving naming conflict of classes by prefixing the class name with a package name. For example, com.zzz.Circle and com.yyy.Circle are two distinct classes. Although they share the same class name Circle, but they belong to two different packages: com.zzz and com.yyy. These two classes can be used in the same program and distinguished using the fully-qualified class name - package name plus class name. This mechanism is called Namespace Management.
Access Control: Besides public and private, Java has two access control modifiers – protected and default – that are related to package. A protected entity is accessible by classes in the same package and its subclasses. An entity without access control modifier (i.e., default) is accessible by classes in the same package only.
For distributing a collection of reusable classes, usually in a format known as Java Archive (JAR) file.
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.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
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.
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
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.
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());
}
}
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.
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.
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) 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:
Which Java access modifier allows a member to be accessed only by the subclasses in other package?
3) 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].
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."
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.
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.
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.
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.