Java Packages

 Packages

         package in Java is a collection of classes, sub-packages, and interfaces.

         It helps to organize your classes into a folder structure and make it easy to locate and use them.

        More importantly, it helps to improve code reusability.

         Packages in Java can be categorized in two forms, built-in packages and user-defined packages.

         There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, SQL, etc.

  Built-in Packages in Java 

To use a class or a package from the library, you need to use the import keyword:

Syntax:

import package.name.class;

import package.name.*;

For example to import a package in the program

import java.util.*;

import java.applet.Applet;


How to create our own package in Java

First create a directory within the name of the package.

Create a java file in a newly created directory.

In this java file you must specify the package name with the help of the package keyword.

Save this file with the same name as the public class

Example 01: 

package pack1;

public class Demo

{

         public void show()

         {

                 System.out.println(“Package called”);

         }

}

After that use this package in your program

import pack1.*;

class A

{

         public static void main(String args[])

         {

                 Demo d=new Demo();

                 d.show();

         }

}




Post a Comment

0 Comments