- Packages in Java
- Types of packages
- User defined packages in Java
- Creating packages in Java
- Java package program
- Compilation and execution of package program
- Can a class have multiple package declaration ?
- Can multiple classes have same package declaration ?
- Creating .class files in separate directory
- What if JVM doesn’t find the .class file at location given by cp/classpath option ?
- Java package program with multilevel directory
- Advantages of Packages
- Creating a Package
- Creating and Using Packages
Packages in Java
As in our computer we have directories to organize the files, similarly in java we have packages, used to organize the classes and interfaces files in java applications. Packages are very similar as directories which help us to write better and manageable code.
A package, as the name itself suggest is a group(pack) of similar types of classes and interfaces. Classes with similar type of functionalities are put together inside a package. It’s the programmer who creates the package and adds the classes and interfaces inside that package.
A package can contain other types as well like enums, annotation types, subpackages. For simplicity we are referring classes and interfaces only, specially the classes in this tutorial.
The image below shows a hierarchy of different java elements where each element is a subset of next element. For example a method is a group of statements, similarly an application is a group of packages.
A package declaration looks like below :
package
packagename; Example:package
mypack;package
com.refreshjava.mypack;
Here package is a keyword while packagename is the name of package given by programmer. As per java the naming of packages should be in small letters only.
Types of packages
Packages can be categorized in two types :
This tutorial covers only user defined packages. For built-in packages refer built in packages tutorial.
User defined packages in Java
Packages defined by programmer is known as user defined packages. While working for an application/project you may need to create one or more packages in your application. Each packages may have one or more classes and interfaces inside it. Let’s see how to create a user defined package.
Creating packages in Java
As mentioned above, a package is also a directory. Each package that you define is a directory in your computer. For example a package name mypack will be a directory mypack inside your computer. Similarly a package name com.refreshjava.mypack will have a directory structure as com/refreshjava/mypack , where directory mypack will be inside refreshjava directory which will be inside com directory.
So to create a package, first you need to create a directory anywhere in your computer. You can also declare the package in your program first and then create the directory with same name(as package name) in your computer. Let’s create a directory mypack inside the computer. In my computer it is created inside D:\project directory, you can choose your own directory. Currently mypack is just an empty directory.
Once you have created the directory, you can use that directory as package name in your program. Remember the package name declaration must be the first statement in your program.
package
packagename; class
className < . >Example: package
mypack; class
Test
Now let’s create the class MyFirstPackageProgram.java as given below inside the D:\project\mypack\ directory.
Java package program
package
mypack;class
MyFirstPackageProgram <public static void
main(String args []) < System.out.println("My first package program"
); printMessage(); >public static void
printMessage() < System.out.println("Inside printMessage method"
); > >
Notice here the package name and directory name is same. A package program must be saved inside it’s own(package name) directory. Now let’s see how to compile and execute the program.
Compilation and execution of package program
If you are not using tools like Eclipse, Netbeans etc, the compilation and execution of programs having package declaration is a bit tricky. To compile above program, open command prompt and move to the directory D:\project or the one that you have used. Execute the below command which will create the .class file inside mypack directory.
javac mypack\MyFirstPackageProgram.java
Now let’s see how to run the above program. To run a package program you need to give the class name with it’s package name while executing the program like below :
java mypack.MyFirstPackageProgram
While compiling or executing the program, ensure that you are in D:\project directory in command prompt or the one you have used for your package directory.
My first package program Inside printMessage method
It’s mandatory to give the class name with it’s package name while running the program since java looks for the .class file in same directory(package name).
Can a class have multiple package declaration ?
No a class can have only one package declaration. Declaring multiple package will result in compilation error.
Can multiple classes have same package declaration ?
Yes multiple classes can have same package declaration. All these class files must go inside same directory.
Creating .class files in separate directory
In above program we created the .class file in mypack directory but in real world applications, generally we use to create the .class files in separate directory like classes or build directory. It’s good programming style to separate the source code and compiled code. To create .class files in separate directory java provides -d option which is used with javac command.
The -d option with javac command is used to specify the directory where the .class files needs to be stored. Create a folder classes inside D:\project directory in your computer and then execute the below command, it will create the .class file inside classes directory.
javac -d classes mypack\MyFirstPackageProgram.java
Here after -d option you need to specify the directory name where to save the .class file. Here it’s classes directory. The .class file will be generated inside D:\project\classes directory, so ensure that it already exist. After successful compilation java compiler will create a directory mypack inside classes directory.
If you want to save the .class files in current or same directory, you can use .(dot) after -d option which tells the java compiler to save the .class file in current directory.
Now to run the program you need to specify -classpath or -cp command line option with java command. This option tells the java virtual machine where to look for .class files.
java -cp classes mypack.MyFirstPackageProgram // or
java -classpath classes mypack.MyFirstPackageProgram
Here after -cp or -classpath option you need to specify the directory name where to look for the .class file. In this case it’s classes directory where jvm will look for .class file. To get more detail about classpath refer Path and Classpath tutorial.
My first package program Inside printMessage method
What if JVM doesn’t find the .class file at location given by cp/classpath option ?
JVM will throw error like «Could not find or load main class . «.
Java package program with multilevel directory
The program below demonstrates the package having multilevel directory structure. Create the directory structure com/refreshjava/mypack inside D:\project directory and then save below program inside that directory.
package
com.refreshjava.mypack;class
PackageDemo <public static void
main(String args []) < System.out.println("Package with multilevel directory"
); > >
Execute below commands to compile and run the program.
javac -d classes com\refreshjava\mypack\PackageDemo.java
java -cp classes com.refreshjava.mypack.PackageDemo
Package with multilevel directory
Advantages of Packages
The advantages of using packages are :
- Packages makes easy to search or locate class or interface files.
- Packages helps to avoid naming conflict. Classes with same name can exist in different packages.
- It also helps in controlling the access of one class inside other class.
- Packages helps in encapsulation of classes and interfaces.
- Packages helps to reuse the classes and interfaces.
- Java’s predefined packages are available in rt.jar file in bin folder of JRE.
- Though you can use capital letters as well for package name but prefer to use small letters only.
- In organizations, generally packages are named in reverse order of domain names like com.orgname or org.orgname , for example com.refreshjava.mypack.
- Programmer should avoid to use the word java for naming their packages like java, java.xyz, java.refreshjava etc, since java uses this word for java packages.
- Every class is part of some package. If no package is specified, the class goes inside a default package(the current working directory) which has no name.
Creating a Package
To create a package, you choose a name for the package (naming conventions are discussed in the next section) and put a package statement with that name at the top of every source file that contains the types (classes, interfaces, enumerations, and annotation types) that you want to include in the package.
The package statement (for example, package graphics; ) must be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.
Note: If you put multiple types in a single source file, only one can be public , and it must have the same name as the source file. For example, you can define public class Circle in the file Circle.java , define public interface Draggable in the file Draggable.java , define public enum Day in the file Day.java , and so forth.
You can include non-public types in the same file as a public type (this is strongly discouraged, unless the non-public types are small and closely related to the public type), but only the public type will be accessible from outside of the package. All the top-level, non-public types will be package private.
If you put the graphics interface and classes listed in the preceding section in a package called graphics , you would need six source files, like this:
//in the Draggable.java file package graphics; public interface Draggable < . . . >//in the Graphic.java file package graphics; public abstract class Graphic < . . . >//in the Circle.java file package graphics; public class Circle extends Graphic implements Draggable < . . . >//in the Rectangle.java file package graphics; public class Rectangle extends Graphic implements Draggable < . . . >//in the Point.java file package graphics; public class Point extends Graphic implements Draggable < . . . >//in the Line.java file package graphics; public class Line extends Graphic implements Draggable
If you do not use a package statement, your type ends up in an unnamed package. Generally speaking, an unnamed package is only for small or temporary applications or when you are just beginning the development process. Otherwise, classes and interfaces belong in named packages.
Creating and Using Packages
To make types easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups of related types into packages.
Definition: A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces.
The types that are part of the Java platform are members of various packages that bundle classes by function: fundamental classes are in java.lang , classes for reading and writing (input and output) are in java.io , and so on. You can put your types in packages too.
Suppose you write a group of classes that represent graphic objects, such as circles, rectangles, lines, and points. You also write an interface, Draggable , that classes implement if they can be dragged with the mouse.
//in the Draggable.java file public interface Draggable < . >//in the Graphic.java file public abstract class Graphic < . >//in the Circle.java file public class Circle extends Graphic implements Draggable < . . . >//in the Rectangle.java file public class Rectangle extends Graphic implements Draggable < . . . >//in the Point.java file public class Point extends Graphic implements Draggable < . . . >//in the Line.java file public class Line extends Graphic implements Draggable
You should bundle these classes and the interface in a package for several reasons, including the following:
- You and other programmers can easily determine that these types are related.
- You and other programmers know where to find types that can provide graphics-related functions.
- The names of your types won’t conflict with the type names in other packages because the package creates a new namespace.
- You can allow types within the package to have unrestricted access to one another yet still restrict access for types outside the package.