Core JAVA

Packages in Java

A package is a group of similar types of classes, interfaces and sub-packages. Package can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. In this page, we will have the detailed learning of creating user-defined packages.

Advantage of Package:

  • Package is used to categorize the classes and interfaces so that they can be easily maintained.
  • Package provids access protection.
  • Package removes naming collision.

Some of the existing packages in Java are:

  • java.lang – bundles the fundamental classes
  • java.io – classes for input , output functions are bundled in this package

Programmers can define their own packages to bundle group of classes/interfaces etc. It is a good practice to group related classes implemented by you so that a programmers can easily determine that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won’t be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classed.


Creating a package:

When creating a package, you should choose a name for the package and put a package statement with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.

The package statement should 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. 

If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an unnamed package.

Example:

Let us look at an example that creates a package called animals. It is common practice to use lowercased names of packages to avoid any conflicts with the names of classes, interfaces.
Put an interface in the package animals:

/* File name : Animal.java */
package animals;

interface Animal {
   public void eat();
   public void travel();
}

Now put an implementation in the same package animals:

package animals;

/* File name : MammalInt.java */
public class MammalInt implements Animal{

   public void eat(){
      System.out.println("Mammal eats");
   }

   public void travel(){
      System.out.println("Mammal travels");
   } 

   public int noOfLegs(){
      return 0;
   }

   public static void main(String args[]){
      MammalInt m = new MammalInt();
      m.eat();
      m.travel();
   }
} 

Now you compile these two files and put them in a sub-directory called animals and try to run as follows:

$ mkdir animals
$ cp Animal.class MammalInt.class animals
$ java animals/MammalInt
Mammal eats
Mammal travels

How to access package from another package?

There are three ways to access the package from outside the package.
  1. import package.*;
  2. import package.classname;
  3. fully qualified name.
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.

The import keyword is used to make the classes and interface of another package accessible to the current package.

Example of package that import the packagename.*

//save by A.java

package pack;
public class A{
  public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
  public static void main(String args[]){
   A obj = new A();
   obj.msg();
  }
}

Output:
Hello

Note: If you import package.classname then only declared class of this package will be accessible but not subpackages.

Example of package by import package.classname

//save by A.java

package pack;
public class A{
  public void msg(){System.out.println("Hello");}
}

//save by B.java

package mypack;
import pack.A;

class B{
  public static void main(String args[]){
   A obj = new A();
   obj.msg();
  }
}

Output:
Hello

Note: If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.

Example of package by import fully qualified name

//save by A.java

package pack;
public class A{
  public void msg(){System.out.println("Hello");}
}

//save by B.java

package mypack;
class B{
  public static void main(String args[]){
   pack.A obj = new pack.A();//using fully qualified name
   obj.msg();
  }
}

Output:
Hello

Note: Sequence of the program must be package then import then class.

Subpackage
Package inside the package is called the subpackage. It should be created to categorize the package further. Let’s take an example, Sun Microsystem has definded a package named java that contains many classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in net packages and so on.

// File Name: Dell.java

package com.apple.computers;
public class Dell{
      
}
class Ups{
      
}

Now compile this file as follows using -d option:

$javac -d . Dell.java

This would put compiled files as follows:

.comapplecomputersDell.class
.comapplecomputersUps.class

You can import all the classes or interfaces defined in comapplecomputers as follows:

import com.apple.computers.*;

Note: If you import a package, all the classes and interface of that package will be imported excluding the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.


Set CLASSPATH System Variable:

To display the current CLASSPATH variable, use the following commands in Windows and Unix (Bourne shell):

  • In Windows -> C:> set CLASSPATH
  • In Unix -> % echo $CLASSPATH

To delete the current contents of the CLASSPATH variable, use :

  • In Windows -> C:> set CLASSPATH=
  • In Unix -> % unset CLASSPATH; export CLASSPATH

To set the CLASSPATH variable:

  • In Windows -> set CLASSPATH=C:usersjackjavaclasses
  • In Unix -> % CLASSPATH=/home/jack/java/classes; export CLASSPATH

<<Previous <<   || Index ||   >>Next >>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago