Java Package With Examples

Java Packages

The mechanism to organize our classes, interfaces, etc on the basis of its functionality, commonalities, and providing access and namespace protection in our development environment is because of packages. We as a developer need to develop loads of classes and its maintenance require proper organization. So package gives this namespace, which isolates it from the rest, as a result, no issue occurs if we have two or more classes with the same name in different packages. Access control to a set of elements can be done at once using a package.

Create Package

In order to create a package, we need to write as

package <MeaningfulName>; 

It should be written in the first line of our source code. By source code, we mean a collection of classes, interfaces, etc in the file that we want to be located inside the package. We cannot have multiple package statements, as we want our entities to be inside one package only.

Example:

package MyPackage;
class myClass{
//data and methods
}

The impact of such a statement after compilation:

  1. A folder of the name MyPackage can be found inside our current working directory.
  2. MyClass.class will be saved inside the folder MyPackage.

Let us look at one example:

Our current working environment is D:\WORKSPACE FOR DEVELOPMENT\JAVA Development\RMMS\src

package com;
public class Customer {
private String name;
private double discount;
private String status;

//Parameterized Constructor
public Customer(String name, String status) {    
                this.name = name;
                this.status = status;        
                setDiscount();  
}

//getter and setter method
public String getName(){
       return name;
}

public void setName(String name){
       this.name = name;
}

public double getDiscount(){
        return discount;
}

public String getStatus() 
       return status;
}

public void setStatus(String status) {
       this.status = status;
       setDiscount();
}

public void setDiscount(){ 
       if(this.status.equalsIgnoreCase("Active"))
               this.discount=5;
       else if(this.status.equalsIgnoreCase("VIP"))
               this.discount=10;
       else
               this.discount=0;

}
}

Upon compilation, when we refer to the directory, we see:

Create Sub-Package

In order to create a package inside an existing package, we need to write as:

package <OuterPackage>.< InnerPackage>; 

This will be written in the first line of our source code. The number of layers of such a sub-package is completely up to the necessity and convenience of the developer.

Let us write a package innerpackage inside the earlier created com package.

package com. innerpackage;
public class MenuItem {

private int itemNumber;
private String itemName;
private String description;
private double itemPrice;

//Default Constructor
public MenuItem() {
this.itemNumber = 0;
this.itemName = "NA";
this.description = "NA";
this.itemPrice = 0;
}

//Parameterized Constructor
public MenuItem(int itemNumber, String itemNname, String description, double itemPrice) {
this.itemNumber = itemNumber;
this.itemName = itemNname;
this.description = description;
this.itemPrice = itemPrice;
}               
}

Upon compilation, when we refer to the directory, we see:

Use an existing Package

In order to use a specific package, we use import. The package members are accessible upon import. We need to import the package in order to use its members.

There are several conventions to import,  which differs on the basis of necessity.

Format Significance
import com.*; Have access to all the sub-packages, direct class, and interfaces
import com.innerpackage.*; Have access to only the innerpackage and its subsequent members.
Import com.innerpackage.menuItem; The strictest access. It gives access to only the class menuItem for use.

Let us look at some examples by importing a pre-defined package java.util.

Example: Here we can access all the classes inside the util package.

import java.util.*;
public class HelloWorld{
     public static void main(String []args){
        Scanner sc = new Scanner(System.in);
        Date dt = new Date();
     }
}

Let us modify the import statement and see the difference

import java.util.Scanner;
public class HelloWorld{
     public static void main(String []args){
        Scanner sc = new Scanner(System.in);
        Date dt = new Date();
     }
}

Output:

HelloWorld.java:6: error: cannot find symbol
        Date dt = new Date();
        ^
  symbol:   class Date
  location: class HelloWorld
HelloWorld.java:6: error: cannot find symbol
        Date dt = new Date();
                      ^
  symbol:   class Date
  location: class HelloWorld
2 errors

We can see that since only the Scanner class is imported, we cannot access any other member of com.innerpackage.

This was an overview of Java Packages. We will discuss Encapsulation in the next lecture.