articles

Home / DeveloperSection / Articles / Package in Java

Package in Java

Manoj Pandey 2237 24-Apr-2015

A package is a namespace that organizes a set of related classes and interfaces.

Package is a collection of classes, interfaces, multiple sub packages etc.

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

Advantages of packages -:

·   Reusability:  Reusability of code is one of the most important requirements in the software industry. Reusability saves time, effort and also ensures consistency. A class once developed can be reused by any number of programs wishing to incorporate the class in that particular program.

·      Easy to locate the files.

·    In real life situation there may arise scenarios where we need to define files of the same name. This may lead to “name-space collisions”. Packages are a way of avoiding “name-space collisions”.


Types of package:

1.      User defined package: The package we create is called user-defined package.


2.      Built-in package: The already defined package like java.io.*, java.lang.* etc are
known as built-in packages


// define package
package packagename;
// import packages
Import mypack;
//class declaration
class Sample
{
// instance members
//method implementation
}
}

 

 

  Package in Java

 

Define a package

package  <package name>;

Example of package of creation

package mypack;

class Book

{

 String bookname;

 String author;

 Book(String b, String c)

 {

  this.bookname = b;

  this.author = c;

 }

 public void show()

 {

  System.out.println(bookname+" "+ author);

 }

}

 

class test

{

 public static void main(String[] args)

 {

  Book bk = new Book("java","Herbert");

  bk.show();

 }

}

 

Access of package-:

Import.mypack;

import java.util.Date;

Subpackage in java-:

Package inside the package is called the subpackage. It should be created to categorize the package further.

Example of sub packages

package com.midstick.core;  
class Sample{ 
  public static void main(String args[]){ 
   System.out.println("Demo subpackage"); 
  } 
}


package com.mindstick.core
import static java.lang.Math.*;
public class Test
{
    public static void main(String[] args)
    {
        System.out.println(sqrt(144));
    }
}

output -: 12  

 


Updated 07-Sep-2019

Leave Comment

Comments

Liked By