Packages in Java

by anupmaurya
0 comment

In this article, you’ll learn about Packages in Java, Advantages of Packages , Types of Packages, Creating a Package and The “import” keyword .

  • A package is a mechanism to group the similar type of classes, interfaces and sub-packages and provide access control.  
  • It organizes classes into single unit.
  • In Java already many predefined packages are available, used while programming.

For example: java.lang, java.io, java.util etc.

Advantages of Packages

  • Packages provide code reusability, because a package has group of classes.
  • It helps in resolving naming collision when multiple packages have classes with the same name.
  • Package also provides the hiding of class facility. Thus other programs cannot use the classes from hidden package.
  • Access limitation can be applied with the help of packages.
  • One package can be defined in another package.

Types of Packages

There are two types of packages available in Java.

1. Built-in packages
Built-in packages are already defined in java API. For example: java.util, java.io, java,lang, java.awt, java.applet, java.net, etc.
2. User defined packages
The package we create according to our need is called user defined package.

Creating a Package

We can create our own package by creating our own classes and interfaces together. The package statement should be declared at the beginning of the program.
Syntax:

package <packagename>;
class ClassName
{
……..
……..
}

Example: Creating a Package

// Demo.java
package p1;
class Demo
{
   public void m1()
   {
       System.out.println("Method m1..");
   }
}


How to compile?

Syntax:  javac –d directory javafilename
For Example: javac –d . Demo.java

How to run?

To run: java p1.Demo

Example: Program to create and use a user defined ackage in Java.

// Vehicle.java package vehicles; interface Vehicle { public void run(); public void speed(); } //Bike.java package vehicles; public class Bike implements Vehicle { public void run() { System.out.println("Bike is running."); } public void speed() { System.out.println("Speed of Bike: 50 Km/h"); } public static void main(String args[]) { Bike bike = new Bike(); bike.run(); bike.speed(); } }
Code language: PHP (php)

Compile

javac –d . Vehicle.java
javac –d . Bike.java

Run

java vehicles.Bike

Output

Bike is running
Speed of Bike: 50 Km/h

The “import” keyword

  • The import keyword provides the access to other package classes and interfaces in current packages.
  • “import” keyword is used to import built-in and user defined packages in java program.


There are different 3 ways to access a package from other packages.

1. Using full qualified name

Example

class Demo extends java.util.Scanner
{
    //statements
}

2. import only single class

Example

import java.util.Scanner;
class Demo
{
      // statements
}

3. import all classes

Example

import java.util.*;
class Demo
{
    // statements
}

You may also like