0% found this document useful (0 votes)
23 views

Packages in Java How To Create and Use Packages in Java

Uploaded by

gowolo4077
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Packages in Java How To Create and Use Packages in Java

Uploaded by

gowolo4077
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Packages in Java: How to Create and Use Packages in Java?

edureka.co/blog/packages-in-java

June 24, 2019

1 / 11 Blog from Objects and Classes


One of the most innovative features of Java is the concept of packages. Packages in Java are a way
to encapsulate a group of classes, interfaces, enumerations, annotations, and sub-packages.
Conceptually, you can think of java packages as being similar to different folders on your computer. In
this tutorial, we will cover the basics of packages in Java.

Listed below are the topics covered in this article:

What is Package in Java?


Java package is a mechanism of grouping similar type of classes, interfaces, and sub-classes
collectively based on functionality. When software is written in the Java programming language, it can
be composed of hundreds or even thousands of individual classes. It makes sense to keep things
organized by placing related classes and interfaces into packages.

Using packages while coding offers a lot of advantages like:

Re-usability: The classes contained in the packages of another program can be easily
reused
Name Conflicts: Packages help us to uniquely identify a class, for example, we can
have company.sales.Employee and company.marketing.Employee classes
Controlled Access: Offers access protection such as protected classes, default classes
and private class
Data Encapsulation: They provide a way to hide classes, preventing other programs
from accessing classes that are meant for internal use only
Maintainance: With packages, you can organize your project better and easily locate
related classes

It’s a good practice to use packages while coding in Java. As a programmer, you can easily figure out
the classes, interfaces, enumerations, and annotations that are related. We have two types of
packages in java.

Types of Packages in Java


Based on whether the package is defined by the user or not, packages are divided into two
categories:

1. Built-in Packages

1/10
2. User Defined Packages

Built-in Packages
Built-in packages or predefined packages are those that come along as a part of JDK (Java
Development Kit) to simplify the task of Java programmer. They consist of a huge number of
predefined classes and interfaces that are a part of Java API’s. Some of the commonly used built-in
packages are java.lang, java.io, java.util, java.applet, etc. Here’s a simple program using a built-in
package.

1 package Edureka;

2 import java.util.ArrayList;

3 class BuiltInPackage {

4 public static void main(String[] args) {

5 ArrayList<Integer> myList = new ArrayList<>( 3 );

6 myList.add( 3 );

7 myList.add( 2 );

8 myList.add( 1 );

9 System.out.println( "The elements of list are: " + myList);

}
10
}
11

12

13

14

15

16

Output:

1 The elements of list are: [3, 2, 1]

2/10
The ArrayList class belongs to java.util package. To use it, we have to import the package using the
import statement. The first line of the code import java.util.ArrayList imports the java.util package and
uses ArrayList class which is present in the sub package util.

User Defined Packages


User-defined packages are those which are developed by users in order to group related classes,
interfaces and sub packages. With the help of an example program, let’s see how to create
packages, compile Java programs inside the packages and execute them.

Creating a Package in Java


Creating a package in Java is a very easy task. Choose a name for the package and include a
package command as the first statement in the Java source file. The java source file can contain the
classes, interfaces, enumerations, and annotation types that you want to include in the package. For
example, the following statement creates a package named MyPackage.

Java Certification Training Course


Instructor-led Sessions
Real-life Case Studies
Assignments
Lifetime Access

1 package MyPackage;

The package statement simply specifies to which package the classes defined belongs to..

Note: If you omit the package statement, the class names are put into the default package, which has
no name. Though the default package is fine for short programs, it is inadequate for real
applications.

Including a Class in Java Package

3/10
To create a class inside a package, you should declare the package name as the first statement of
your program. Then include the class as part of the package. But, remember that, a class can have
only one package declaration. Here’s a simple program to understand the concept.

1 package MyPackage;

2 public class Compare {

3 int num1, num2;

4 Compare( int n, int m) {

5 num1 = n;

6 num2 = m;

7 }

8 public void getmax(){

9 if ( num1 > num2 ) {

10 System.out.println( "Maximum value of two numbers is " + num1);

}
11
else {
12
System.out.println( "Maximum value of two numbers is " + num2);
13
}
14
}
15
public static void main(String args[]) {
16
Compare current[] = new Compare[ 3 ];
17
current[ 1 ] = new Compare( 5 , 10 );
18
current[ 2 ] = new Compare( 123 , 120 );
19
for ( int i= 1 ; i < 3 ; i++)
20
{
21
current[i].getmax();
22
}
23
}
24
}
25

4/10
26

27

28

29

30

31

Output:

1 Maximum value of two numbers is 10

2 Maximum value of two numbers is 123

As you can see, I have declared a package named MyPackage and created a class Compare inside
that package. Java uses file system directories to store packages. So, this program would be saved
in a file as Compare.java and will be stored in the directory named MyPackage. When the file gets
compiled, Java will create a .class file and store it in the same directory. Remember that name of the
package must be same as the directory under which this file is saved.

You might be wondering how to use this Compare class from a class in another package?

Creating a class inside package while importing another package


Well, it’s quite simple. You just need to import it. Once it is imported, you can access it by its name.
Here’s a sample program demonstrating the concept.

5/10
1 package Edureka;

2 import MyPackage.Compare;

3 public class Demo{

4 public static void main(String args[]) {

5 int n= 10 , m= 10 ;

6 Compare current = new Compare(n, m);

7 if (n != m) {

8 current.getmax();

9 }

10 else {

System.out.println( "Both the values are same" );


11
}
12
}
13
}
14

15

Output:

1 Both the values are same

I have first declared the package Edureka, then imported the class Compare from the package
MyPackage. So, the order when we are creating a class inside a package while importing another
package is,

Package Declaration
Package Import

Well, if you do not want to use the import statement, there is another alternative to access a class file
of the package from another package. You can just use fully qualified name while importing a class.

Programming & Frameworks Training

Using fully qualified name while importing a class

6/10
Here’s an example to understand the concept. I am going to use the same package that I have
declared earlier in the blog, MyPackage.

1 package Edureka;

2 public class Demo{

3 public static void main(String args[]) {

4 int n= 10 , m= 11 ;

5 //Using fully qualified name instead of import

6 MyPackage.Compare current = new MyPackage.Compare(n, m);

7 if (n != m) {

8 current.getmax();

}
9
else {
10
System.out.println( "Both the values are same" );
11
}
12
}
13
}
14

Output:

1 Maximum value of two numbers is 11

In the Demo class, instead of importing the package, I have used the fully qualified name such as
MyPackage.Compare to create the object of it. Since we are talking about importing packages, you
might as well check out the concept of static import in Java.

Static Import in Java


Static import feature was introduced in Java from version 5. It facilitates the Java programmer to
access any static member of a class directly without using the fully qualified name.

7/10
1 package MyPackage;

2 import static java.lang.Math.*; //static import

3 import static java.lang.System.*; // static import

4 public class StaticImportDemo {

5 public static void main(String args[]) {

6 double val = 64.0 ;

7 double sqroot = sqrt(val); // Access sqrt() method directly

8 out.println( "Sq. root of " + val + " is " + sqroot);

9 //We don't need to use 'System.out

10 }

11 }

Output:

1 Sq. root of 64.0 is 8.0

Though using static import involves less coding, overusing it might make program unreadable and
unmaintainable. Now let’s move on to the next topic, access control in packages.

Access Protection in Java Packages


You might be aware of various aspects of Java’s access control mechanism and its access specifiers.
Packages in Java add another dimension to access control. Both classes and packages are a means
of data encapsulation. While packages act as containers for classes and other subordinate packages,
classes act as containers for data and code. Because of this interplay between packages and
classes, Java packages addresses four categories of visibility for class members:

Sub-classes in the same package


Non-subclasses in the same package
Sub-classes in different packages
Classes that are neither in the same package nor sub-classes

The table below gives a real picture of which type access is possible and which is not when using
packages in Java:

Private No Modifier Protected Public

8/10
Same Class Yes Yes Yes Yes

Same Package Subclasses No Yes Yes Yes

Same Package Non-Subclasses No Yes Yes Yes

Different Packages Subclasses No No Yes Yes

Different Packages Non- Subclasses No No No Yes

We can simplify the data in the above table as follows:

1. Anything declared public can be accessed from anywhere


2. Anything declared private can be seen only within that class
3. If access specifier is not mentioned, an element is visible to subclasses as well as to other
classes in the same package
4. Lastly, anything declared protected element can be seen outside your current package, but
only to classes that subclass your class directly

This way, Java packages provide access control to the classes. Well, this wraps up the concept of
packages in Java. Here are some points that you should keep in mind when using packages in Java.

Points to Remember
Every class is part of some package. If you omit the package statement, the class names are
put into the default package
A class can have only one package statement but it can have more than one import package
statements
The name of the package must be the same as the directory under which the file is saved
When importing another package, package declaration must be the first statement, followed by
package import

Well, this brings us to the end of this ‘Packages in Java’ article. We learned what a package is and
why we should use them. There is no doubt that Java package is one of the most important parts for
efficient java programmers. It not only upgrades the programmer’s coding style but also reduces a lot
of additional work.

If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java
Concepts.

9/10
Java Certification Training Course
Weekday / Weekend Batches

If you found this article on “Packages in Java”, check out the Java Course Online by Edureka, a
trusted online learning company with a network of more than 250,000 satisfied learners spread
across the globe. We are here to help you with every step on your journey, for becoming a besides
this java interview questions, we come up with a curriculum which is designed for students and
professionals who want to be a Java Developer. Join our Java Training in Cambridge today.

Upcoming Batches For Java Certification Training Course

10/10

You might also like