Packages in Java Explained

Packages in Java Explained

5 mins read1.3K Views Comment
Updated on Oct 25, 2023 17:04 IST

The below article goes through packages in Java along with its implementation ways and accessibility. It also uses several examples for the explanation.

2022_06_Untitled-design-20.jpg

A package in Java can be viewed as a directory/folder which comprises a set of related classes and interfaces. It’s a way to organize various java resources. They are also used to avoid namespace collisions as it allows us to create multiple classes with the same name as far as they are in different packages.

Explore popular Java Courses

Table of Content

Also Read: OOPs concepts in Java

Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

– / –
6 weeks
β‚Ή15 K
3 months
β‚Ή2.05 K
3 months
– / –
170 hours
β‚Ή5.4 K
1 month
– / –
6 months
– / –
2 months
β‚Ή17 K
3 months
β‚Ή5.5 K
1 month

What are Packages in Java?

Packages in Java are a way of grouping a set of associated classes and interfaces. For instance, a package named development comprises all the development tools for a specific language. One can use the same name for two classes till the time they reside in different packages.

Read: Interfaces in Java

How to define a Package in Java?

Explore- Top Java Project Ideas for Beginners to Try

A package can be defined using the keyword package. The following statement creates a package pkg and puts class A under it.

Syntax

package mypackage;

import java.util.ArrayList;
// other imports

public class MyClass {
    // class body
}

In this example, mypackage is the name of the package, and MyClass is a class within that package.

Also read: Method Overriding in Java

Hierarchy of Packages in Java

You can create a hierarchy of packages by building packages inside other packages. For example, the predefined package math resides inside another predefined package in java. To access such packages, we specify a dot in between the two packages. 

Example: java.math denotes access to the math package inside the java package.

Therefore to create a multilevel hierarchy of packages, one can use the following syntax:

package pk1.pk2.pk3;

All the classes and interfaces using the above package statement will be a part of the pk3 package residing inside the pk2 package, which is under the pk1 package.

Also, Read: Data Types in Java – Primitive and Non-Primitive Data Types Explained

Accessing Package Members

There can be times when members of one package are to be used in another package. In such cases, we can follow one of the  following given approaches:

Using a fully qualified name

A fully qualified name refers to the package name along with the member name. 

Example: 


 
package pkg1;
public class A
{
public int a = 10; //public member in pkg1
}
package pkg2;
public class B {
int b; //member of package pkg2 with default acccess
void setB() {
pkg1.A obj = new pkg1.A(); //accessing class A using fully qualified name
b=2*obj.a;
System.out.println("The value of a: " +obj.a);
System.out.println("The value of b: " +b);
}
}
Copy code

Explanation:

We have 2 classes A and B belonging to different packages pkg1 and pkg2 respectively. To access a member of package pkg1, one needs to create an object of class A using the fully qualified name of class A along with its package. Here, the member a of package pkg1 could be accessed outside its own package because of its public nature.

Read: Implementing Array in Java

Importing a package member

You can import the package member which has to be used or accessed in the other package. This can be implemented using an import statement.

Example: 


 
package pkg1;
public class A
{
public int a = 10; //public member in pkg1
}
public class AB
{
public int ab = 15; //public member in pkg1
}
package pkg2;
import pkg1.A; //importing only class A from pkg1
public class B {
int b; //member of package pkg2 with default acccess
void setB() {
A obj = new A(); //accessing class A directly
b=2*obj.a;
System.out.println("The value of a: " +obj.a);
System.out.println("The value of b: " +b);
}
}
Copy code

Explanation:

In the above program, pkg2 imports only class A from pgk1. That means class AB can’t be used inside pkg2. Moreover, once we import the member of the package, we can use it directly without using its fully qualified name.

Read: Conditional Statements in Java

Importing the entire package

If someone requires to import all the classes/members of a package can use the import statement with the package name. 

Example:


 
package pkg1;
public class A
{
public int a = 10; //public member in pkg1
}
public class Aa
{
public int num = 100; //public member in pkg1
}
package pkg2;
import pkg1.*; //importing all the members from pkg1
public class B {
int b; //member of package pkg2 with default acccess
void setB() {
A obj = new A(); //accessing class A directly
b=2*obj.a;
System.out.println("The value of a: " +obj.a);
System.out.println("The value of b: " +b);
}
}
Copy code

Explanation:

Here, β€˜*’ (asterisk) helps to access all the classes and interfaces inside a package.

Note: import pkg1.* can only import classes and interfaces inside pkg1. It can’t import any sub package inside pkg1. For instance, the above statement can’t import class AB inside package pkg12 which resides in pkg1. 

To access class AB you have to write like: 

import pkg1.pkg12.AB;

Read: Exception Handling in Java.

Python vs Java: Which is Better to Learn in 2024?
Difference between Abstract class and Interface in Java
What is Wrapper Class in Java?

Access Control in Packages

Java access modifiers are applicable on packages as well. The below table shows the access specifier of each category of private, protected, public, and default (package-level).

table-access

Also, Read: Access Modifiers in Java

Demonstration of Access Control in Packages

The below example shows the usage of access specifiers or access modifiers with packages.

Example:


 
// Define the packages and classes in a single file for demonstration
// Package pkg1
package pkg1;
public class A {
int var1 = 10; // Default member
protected int var2 = 34; // Protected member
private int var3 = 56; // Private member
public void disp() {
System.out.println("I am a public method!");
}
}
class AB {
// Members and methods for AB
}
// Package pkg2
package pkg2;
import pkg1.A;
public class B {
public void samePackage() {
A obj = new A();
System.out.println(obj.var1); // Accessing default variable
System.out.println(obj.var2); // Accessing protected variable
// System.out.println(obj.var3); // Error! var3 is private
obj.disp(); // Accessing public method
}
}
public class C extends A {
public void accessProtected() {
System.out.println(var2); // Accessing protected variable outside its package
}
// Additional methods and members for C
}
// Package pkg3
package pkg3;
import pkg1.*;
public class Main {
public static void main(String[] args) {
A a = new A();
a.disp(); // Public method accessible anywhere
// System.out.println(a.var1); // Error! var1 is default, can't access outside pkg1
// System.out.println(a.var2); // Error! var2 is protected, not directly accessible outside pkg1
// System.out.println(a.var3); // Error! var3 is private
}
}
Copy code

Explanation

  • In reality, each class should ideally be in its own file, especially when they’re public.
  • Accessing private members outside their own class or default members outside their package results in errors.

Check out- Top Java Interview Questions and Answers

Conclusion

Hope you enjoyed reading the above article and learned something new from it. In case you face any queries, feel free to reach out to us at the link below. Happy Learning!

For more, read: 8 Most Important Data Structures a Programmer Must Know

FAQs

What are Packages in Java?

A package in Java can be viewed as a directory/folder which comprises a set of related classes and interfaces. It's a way to organize various java resources.

Why are packages used in Java?

Packages contain all the related classes and interfaces. They are used to avoid namespace collisions as it allows us to create multiple classes with the same name as far as they are in different packages.

How can we directly use packages without using a fully qualified name?

Using an import statement with the package name helps you access the package member directly.

What are the types of Packages in Java?

Packages are divided into two categories: Java API packages or built-in packages and User-defined packages.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio