Pageviews

Wednesday 12 June 2013

How to create User defined packages in Java

by Unknown  |  in Java at  Wednesday, June 12, 2013

Packages can be defined as a method to put Classes,Methods,variables and Interfaces together in a same pack.This grouping is basically done on the basis of functionality.In simpler words,packages act as a container for classes.Packages are an important part of Java,each packages has its own functionality,packages provides following advantages:
  • Classes of a particular package of the other program can be easily reused.
  • Two different packages can have same class name.
  • Packages provides us ways to hide classes from accidental use.

Java supports two types of Packages:

  1. Java API(Application Programming Interface) Packages.
  2. User defined Packages.


1.Java API Packages:The API packages which are already defined in Java are called Java API packages,they are also known as built in packages.For Ex:Java.lang, Java.util, Java.io.

2.User defined packages: Java also supports a functionality that the users can define their own packages.Now the problem arises,that how we can create and run user defined packages in Java.In order to create new user defined package you need to follow  the below steps:

  • Firstly,you need to create a New folder,give it the name,you want to give to your package.
  • Then you need to create a new class outside that folder and then compile the package,remember that you need to compile only the package,you should not run it,because it does not contain any main method.
  • Now create new program whatever you want to create.
  • Then import the package you had created and then compile and run the program.

package Mine;                                                   //New package declared by user
public class packs
 {
public void display()
{
System.out.println("Welcome to World of Java");
}
}                                            

Now create a program outside the Package folder,the following examples shows how we had create a program outside the 'Mine' package folder and then we need to import our package using 'import' keyword,lets see how;

import Mine.*;                                                      //Package is imported
class dort{
public static void main(String args[])
{
packs d=new packs();                                              // Object of Package class is created      
d.display();                                                             //Method of our Package is accessed
}
}

The output goes here:

Packages



















2 comments:

Proudly Powered by Blogger.