'Package' is a word we often come across when we learn java programming language. If you've noticed a java program keenly you'll find that the first line in your program always has this package keyword. For example, "Package MyFile;". Your program always remains incomplete without this word.
Ever wondered what this 'package' actually is? What does it do? or Why is it always in the first line of the program? This article answers all your questions. Come let's dive in!
In Java, a Package is a way to bundle together all the related classes, packages, and interfaces. It is a container for a collection of related classes, some of which are maintained for internal use while others are made accessible and exposed. Existing classes from the packages can be reused within our software as often as necessary.
1) Maintenance of the classes and interfaces are easy because of the categorization.
2) Protection of access can be achieved
3) Collision of similar names can be avoided.(We'll be exploring this further)
4) Organization of the files within a project or a system is easy.
5) Reusability of the same packages can be done. This inturn saves time and efforts.
6) Easy Access of the files is enabled.
7) Data Encapsulation can also be achieved by making use of packages
Packages, in java, are mainly believed to be of two types. They are
Inbuilt Packages: These are the packages that are offered by Java to all the users by default. Example: Util, lang, etc.
User-Defined Packages: These are the pacakges that the user create by themselves
We'll look into these types in depth.
Many precoded classes are offered for free by the Java API, which is a library. This library has many components for different functions such as input management, Programming of database and so much more. The list of these components can be found in the website maintained by the owner of java,Oracle. Check it out.
Some of the inbuilt classes are shown below in the figure. We'll look into them in details further.
Java API offers various inbuilt packages. Some of them are given below.
1) java.lang: This package contains the fundamental classes and interface required in Java langauge. Some of the classes are String, System, Integer, Math, StringBuffer, etc.
2) java.util: This package contains classes that support the user by performing some internal operations like generation of random number, creating an array,linkedlist,hashmap,etc.Some of the classes of this package are TimeZone, Date, Calendar, HashMap, LinkedList, ArrayList,etc.
3) java.sql: Classes to access and process the data in the database are provided in this package. Some of the classes are DriverManager, PreparedStatement, Statement, Connection, ResultSet, etc.
4) java.net: Classes to implement services with respect to networking applications are provided in this package. Some of the classes are Socket, URL, URLEncoder, URLDecoder, URLConnection, HTTPCookie, Authenticator, etc.
5) java.awt: Classes for creating interface for the user and graphic images creation are provided by this package. Some of the classes are Color, Button, Event, Graphics, Font, Image, etc.
6) java.io: Classes for performing all the input and output operations of the system are provided in this package. Some of the classes are InputStream, OutputStream, PrintStream, BufferedReader, BufferedWriter,etc
Inbuilt classes can be used by using the keyword 'import'. The packages are imported from the Java Development Environment and used in the program.
We have 3 ways to import packages:
1) To import a whole package the (*) sign is used.
2) To import a specific class from the package, the class name has to be specified followed by the package name.
3) To import different subclasses from a package the fully qualified name must be used. A fully classified name in java includes the package that the class was created from.
Refer the code snippet below for the illustrations of the above.
As the name suggests, these are the pacakges defined or created by the user. The user has the freedom to create classes, import other packages or create interfaces inside their own package. This offers flexibility to the user and makes it easy for the user to understand their code.
Java uses a directory like file structure to store these packages. This resembles the folders in our personal computers.
User Defined packages can be created in a simple way by using the 'package' keyword. An example is given below in the code snippet.
In the above snippet we can see that the package 'MyPackage' has been created using the 'package' keyword. A class called 'PackageClass1' has been created in this package.
To access this package we must follow some steps. They are as follows. Enter the commands in the terminal.
Save your file as PackageClass1.java
Compile your java file.
Run the file through the terminal.
You can find the following output
A package that is defined within another package can be defined as a sub-package. It is utilised to increase the package's genericity in terms of structure. Users can organise their Java files into the appropriate packages using this tool.
To understand this concept in a better way, let us take an example of a package named 'food'. Now, say, we want to define another package called 'cakes'. We can define it as a separate package. But it'll be more easy to access if it is defined as a separate package inside the package 'foods'. Hence, 'cakes' can be called as the subpackage under the package 'food'. This also makes it generic. Let us look into the below file structure
The above structure makes it clear that giving proper names to files and keeping them in a package designated is very important to access the required files.
You may be aware that everything in Java is done inside of classes. Therefore, it is necessary to manage the access limitations to data members and methods by separate files for security reasons. In this topic we'll mainly focus on the accessibility on a package-level. As we are aware Java has 4 access-modifiers- Public, Private, Protected and Default.
All other members of a class, excluding its private members, are accessible to all other classes included in the same package. Subclasses established within of various packages can only access members that are public and protected. Let us try to understand these the permissions with the help of a table.
|Acess Modifier||Same Class||Same package non-subclass||Same package subclass||Difference Package subclass||Different package non-subclass|
|Private||Allowed||Not Allowed||Not Allowed||Not Allowed||Not Allowed|
|Default||Allowed||Allowed||Allowed||Not Allowed||Not Allowed|
Lets understand the table in detail.
Same Class: From the above table we can see that if a class X has some data members defined with any access modifiers, be it private, protected, default or public, then it can be accessed inside X.
Same package Non Sub-class: We have more than one classes in one package. If we have two classes inside the same package say, X and Y , and when we try to import the class Y inside class X, then it is possible for class X with every access specifier except for private.
Same package Sub-class: When one class X inherits from another class Y in the same package, it is only possible if the class Y has any access specifier except for private. Protected and Default are also possible to be inherited as they are in the same package.
Different Package Sub-class: Consider we have two packages A and B, with Classes X and Y respectively and class Y is subclass of class X. If Class Y has to access the components of class X, it can only do so if Class X has the access specifier of public or protected.
Different Pacakge Non-Subclass: Consider the same classes X and Y of packages A and B respectively. In this case Y is not a subclass of X. In such cases if Y wants to access data members of X, it can only do so if the access specifiers of X is public.
Usage of Static Import: The Java language (version 5 and above) introduces the concept of static import, which enables members (data members and methods) that are defined inside a class with the label of public static to be used in another Java code without mentioning the class in which they are defined.
Name Conflict Handling: If we notice, the names of some data members or methods of different classes are the same. While importing these packages we might have to use the method or data member of a specific class. This might cause conflicts between names. To avoid this java offers the naming feature where we mention the full package names of each class everytime we declare an object.
The package name is stored in a directory like structure. The components of one directory are stored inside a sub-directory. This makes it easy for users to access the file and it removes complexity in the design structure.
Let us understand this with an example. The class vehicle of package com.logicmojo.package1.subpackage2 is stored as “$BASE_DIR\com\logicmojo\package1\subpackage2\vehicle.class”, where $BASE_DIR is the base directory of the package. The sub-directory is denoted by the dot.
The $BASE_DIR in the above example can be placed anywhere in the file system. To locate this the compiler of java must be made aware about this location. An Environment Variable called CLASSPATH is used for this purpose. This CLASSPATH can be set and removed by the user.
1. In any class there can exist only one package statement but there can be more than one import package statement.
2. Package must be declared with root folder name and the class name must be last file name with a semicolon at the end.
3. Package declaration should be the first statement, While importing another package and it must be followed by importing of packages.
4. Importing a package doesn't give rise to memory allocation. It just file path to access the file.
5. Always import the specific class than *.
This concludes our discussion of "Packages in Java". I hope that you gained knowledge about this amazing feature offered by java and are now more interested to dive into the language. You can consult the Java Tutorial for further guidance.
Good luck and happy learning!