Modal Box

Package in java

In java, similar classes and interfaces may be grouped together into a package.
A package may also have sub packages. Package may be user defined as well as inbuilt package.
With the help of java package we can have same class name .
Access protection may also be provided with java package.
When we don’t put a package there, it means classes are put into default package.

If a class is declared in a packet, then it can be written as follows.
package mypkg;

class PkgExample
{
  public static void main(String args[])
  {
    System.out.println("this is package example class");
  }
}

Compile this java file using command line :

You have to compile as following command if java file is PkgExample.java and in folder named mypkg.

  > javac mypkg\PkgExample.java

To run the java class :

  > java mypkg.PkgExample

Here, mypkg is the name of package and PkgExample is the name of class.

How to import package :

To use the classes of another package, the package needs to be imported.

  import mypkg.*; // this wil import all classes of mypkg package
  import mypkg.PkgExample; // only PkgExample class is imported of package mypkg;

Subpackage in java:

A package within package (sub package) may be declared and imported in java.

package mypkg.subpkg;

class SubPkgExample { public static void main(String args[]) { System.out.println("this is sub package example class"); } }

Sub package classes may be imported as following :

  import mypkg.subpkg.*; // to import all classes of sub package.

Video/ C Introduction

Watch video in full size
Wordpress Social Share Plugin powered by Ultimatelysocial