Register Login

Packages in Java

Updated May 18, 2018

What is package

Package in is a structure which organizes various class files in Java into different folders according to their functionality or categories by user, for example, all the java.io classes will be in java.io package whereas all the java.net classes such as Socket or SeverSocket will be inside java.net package.

Why we require Package in Java?

Package is required in java to differentiate between various types of classes such as java.net,java.io which allows us to access those classes more easily. Same as we keep a sad song, rock music in different sub-folders of folder music.

Creating a New Package

1) Go to your JAVA IDE such as Eclipse, Netbeans

2) Select new java package

3) Give a name to your package

4) Now drag and drop all the classes of similar functionality you want to put in your new created package

Packages Directory Structure

There are multiple things which occur when a class is placed in a package :

  • The package name becomes a part of the name of the class
  • The package name must match the directory structure where the corresponding bytecode belongs.

Importing a Package in a Class

Below is an example of a JAVA program to import package in a class

package packexample;

import packexample.dao.AccDao;

Public class PackExample {

public static void main (String[] args)

{

AccDAO obj = new AccDAO();

}
}

Using a class in a Package

package packxample.dao;

public class ACcDAO {


×