Packages in Java
There are folders or directories in our computers for the classification and accessibility of various files, and in Java, we have packages for the same. In Java, Packages are similar to folders, which are mainly used to organize classes and interfaces.
Packages help us to write better and
manageable code by preventing naming conflicts. Java provides some built-in
packages which we can use but we can also create our own (user-defined)
packages.
In this article, we are going to
discuss everything about packages in Java along with their syntaxes and
examples. Moving forth in this article we are going to learn –
1.
Packages in Java
2.
Advantages of using Packages in Java
3.
Types of Packages in Java
4.
Creating a Package in Java
5.
Example of Java Packages
6.
Package naming Conventions
7.
Compiling a Java Package
8.
Executing Java Package Program
9.
Accessing a Java Package
10. Sub packages in Java
11. Important Points in Java Package
12. Dividing Classes into Packages
Packages in Java
A package is a collection of similar
types of Java entities such as classes, interfaces, subclasses, exceptions,
errors, and enums. A package can also contain sub-packages.
Advantages of using Packages
in Java
There are several advantages of using
Java Packages, some of them, are as follows –
·
Make easy searching or locating of
classes and interfaces.
·
Avoid naming conflicts. For example,
there can be two classes with the name Student in two packages,
university.csdept.Student and college.itdept.Student
·
Implement data encapsulation (or
data-hiding).
·
Provide controlled access: The access
specifiers protected and default have access control on package level. A member
declared as protected is accessible by classes within the same package and its
subclasses. A member without any access specifier that is default specifier is
accessible only by classes in the same package.
·
Reuse the classes contained in the
packages of other programs.
·
Uniquely compare the classes in other
packages.
Get
to know about Access Specifiers in Java you didn’t know about.
We just put similar classes into the
same packages. After that, we simply import the classes from existing packages
through the import statement and use them in our program. A package provides
access to some classes and others are kept for internal purposes.
Note:
·
Package names are dot-separated,
e.g., java.lang.String
·
Packages avoid namespace collision: A
package can not contain two classes with the same names, but two different
packages can have a class with the same name.
·
The exact name of the class is
identified by the structure of its package.
Types of Packages in Java
They can be divided into two
categories:
1.
Java API packages or built-in
packages and
2.
User-defined packages.
1. Java API packages or
built-in packages
Java provides a large number of
classes grouped into different packages based on a particular functionality.
Examples:
java.lang: It contains classes for primitive types,
strings, math functions, threads, and exceptions.
java.util: It contains classes such as vectors, hash
tables, dates, Calendars, etc.
java.io: It has stream classes for Input/Output.
java.awt: Classes for implementing Graphical User
Interface – windows, buttons, menus, etc.
java.net: Classes for networking
java.
Applet: Classes for creating and
implementing applets
2. User-defined packages
As the name suggests, these packages
are defined by the user. We create a directory whose name should be the same as
the name of the package. Then we create a class inside the directory.
Creating a Package in Java
To create a package, we choose a
package name and to include the classes, interfaces, enumerations, etc, inside
the package, we write the package with its name at the top of every source
file.
There can be only one package
statement in each type of file. If we do not write class, interfaces, inside
any package, then they will be placed in the current default package.
Example of Java Package
We can create a Java class inside a
package using a package keyword.
package com.abc.packagedemo;
//package
class Example
{
public static void
main(String args[])
{
System.out.println("Welcome
to abc’s Java Tutorial");
}
}
Output:
Welcome to abc Java Tutorial
How do Packages in Java Work?
The names of packages and the
directory structure are closely related to each other.
For example, if a package name is
university.engineering.csedept, then there are three directories- university,
engineering, and csedept such that csedept is present in engineering and
engineering is present in university.
The package university can be
considered as a top-level package while engineering is a subpackage of
university and cse dept is a sub-package of engineering.
Package Naming Conventions
Packages names follow the reverse
order of domain names, that is, org.abc.tutorials. For example, in a
university, the recommended convention is university.engineering.mech or
university.tech.it or university.arts.history etc.
In the following package:
java.util.Vector
·
java is a top-level package
·
util is a sub package
·
and Vector is
a class which is present in the subpackage util.
Compiling a Java Package
If you are using an IDE (Integrated
Development Environment), then for compiling the package, you need to follow
the syntax given below:
javac
-d directory javaFileName
For
example,
javac
-d . Example.java
-d specifies the destination where to
locate the generated class file. You can use any directory name like /home (in
case of Linux), C:/folderName (in case of windows), etc. If you want the
package to be present in the same directory, you can use the dot ( . )
Executing Java Package Program
You need to use a fully qualified
name e.g. com.abc.MyClass etc to run the class.
To
Compile:
javac
-d . MyClass.java
Here -d represents
the destination. The . represents the current folder.
To
run:
java
com.abc.MyClass
Accessing Packages or Classes
from Another Package
If we want to access all the classes
and interfaces of an existing package then we use the import statement. We can do it in three different
ways:
·
import package.*;
·
import package.classname;
·
fully qualified name.
1. By using * after
the import statement, we can access all the classes of the package but not the sub-packages.
Syntax:
For importing all the classes:
import
packageName.*;
Code
to illustrate the above concept:
package com.abc.packagedemo;
//package
class MyClass
{
public void printName(String
name)
{
System.out.println(name);
}
}
package com.abc.packagedemo1;
import com.abc.packagedemo.*; //importing
all the classes
public class MyClass1
{
public static void
main(String args[])
{
// Initializing the String variable with a value
String name = "abc's Java Tutorial";
// Creating an instance of class MyClass from
another package.
MyClass obj = new
MyClass();
obj.printName(name);
}
}
Output:
abc’s Java Tutorial
2. By using a particular class name after the import statement, we can access
that particular class package but not the sub-packages.
Syntax:
For importing a particular class:
import
packageName.className;
Code
to illustrate the above concept:
package com.abc.packagedemo;
//package
class MyClass
{
public void printName(String
name)
{
System.out.println(name);
}
}
package com.tabc.packagedemo1;
import com.abc.packagedemo.MyClass; //importing
a particular class MyClass
public class MyClass1
{
public static void
main(String args[])
{
// Initializing the String variable with a value
String name = "abc's Java Tutorial";
// Creating an instance of class MyClass from
another package.
MyClass obj = new
MyClass();
obj.printName(name);
}
}
Output:
abc’s Java Tutorial
3. Using a Fully qualified name means we can access the declared class of
different packages without using the import statement. But you need to use a
fully qualified name every time when you are accessing the class or interface
which is present in a different package.
This type of technique is generally
used when two packages have the same class name example class Date is present
in both the packages java.util and java.sql.
Code
to illustrate the above concept:
package com.abc.packagedemo;
//package
class MyClass
{
public void printName(String
name)
{
System.out.println(name);
}
}
package com.abc.packagedemo1;
public class MyClass1
{
public static void
main(String args[])
{
// Initializing the String variable with a value
String name = "abc's Java Tutorial";
// Using fully qualified name to access the class
of different package
com.abc.packagedemo.MyClass obj = new
com.abc.packagedemo.MyClass();
obj.printName(name);
}
}
Output:
abc’s Java Tutorial
Note: If you import a package, you can
not import the sub-packages. If you import a package, all the classes and
interface of that package will be imported but the classes and interfaces of
the sub-packages will not be accessible. Hence, you will have to import the
subpackage as well.
Note: The sequence of the program must
be package name then import statement.After both the class begins.
Subpackage in Java
The package present inside a package
is called the subpackage. It is created to further categorize packages.
For example, If we create a package
inside the abc package then that will be called subpackage.
Let’s say we have created another
package inside abc and the name of subpackage is tutorials. So if we
create a class in this subpackage it should have a package declaration in the
following manner:
package abc.tutorials.classname;
Here abc is a package while
tutorials is a subpackage of abc.
The standard of defining the package is
domain.company.package
example com. abc.tutorials.javatutorial or org.iit.dao.
Code
to explain Subpackage
package com. abc.tutorials.javatutorial;
class Demo
{
public static void
main(String args[])
{
System.out.println("Inside
a sub-package");
}
}
To
compile: javac -d. Demo.java
To
run: java
com. abc.tutorials.javatutorial
Output:
Inside a sub-package
Using Static Import
‘Static Import’ is a feature
introduced in Java programming language for Java versions
5 and above that allows fields and members of a class which are declared as
public and static to be directly used inside the Java code without specifying
the name of the class in which these public static fields or methods are
defined.
Code
to illustrate the use of static import statement
// Note static keyword after import.
package com. abc.packagedemo;
import static java.lang.System.*;
class StaticImportDemo
{
public static void
main(String args[])
{
// We don't need to use 'System.out'
// as we imported the package using static.
out.println(" abc");
}
}
Output:
abc
Important points on Packages
in Java
·
Every class belongs to a package. If
you do not mention any package, the classes in the file move into a special
unnamed package which is the same for all the files which do not belong to a
specified package.
·
Multiple classes and interfaces in a
file can be part of the same package.
·
If the package name is specified,
then the directory name must match the package name.
·
We can access the classes declared as
public in another package using:
import package-name.class-name
Dividing Your Classes Into
Packages
You might be thinking that how to
categorize your classes into packages. There is no standard method to do this
but thee are two methods which you can follow:
1. Divide by Layer
This is the first method in which we
divide the classes according to the layers of the application. For example, if
your application contains a network layer, then you would create a package
named network.
All classes which are related to the
network of the application are located in the network package.
2. Divide by Application
Functionality
You can also divide your classes on
the basis of what part of the application functionality they belong to. Thus,
if your application has a functionality area that calculates interest you would
create a Java package named interest.
All classes related directly or
indirectly to the interest calculations would go into that package. If the
number of classes in the root package becomes very large, they can also be
moved to the sub-packages.
Summary
Packages are essential for better
management and accessing of code. Coming to the end of our tutorial, we learned
about the packages in Java in detail along with its two types.
We also covered the working, the
techniques to access the packages in other packages in Java, with the help of
syntax and coding examples. This will be surely helpful for your further study
of the Java language.
Thank you for reading our article. If
you have any queries related to Packages in Java, do let us know by dropping a
comment below.
Great work guys🤩
ReplyDeleteVery nice information
ReplyDeleteThanks for the Knowledge!
ReplyDeleteNice
ReplyDeleteInformative
ReplyDeleteVery nice and informative
ReplyDelete