Working with packages

Working with packages


Posted in : Core Java Posted on : October 5, 2010 at 4:30 PM Comments : [ 0 ]

In this section , you will learn how to manage package structure.

Working with packages

The package is used due to :

  • prevent naming conflicts

  • to control access

  • to make searching/locating

  • and to make usage of classes, interfaces, enumerations and annotations easier.

Existing package in Java are :

(1) java.lang - bundles the fundamental classes

(2) java.io - classes for input , output functions are bundled in this pack

Creating a package

You can define your own package to wrap up group of classes/interfaces etc. Using package provide effective management of application as all the related things to a project or application are bundled together under the same package.

Due to new name space created by package, there won't be name conflict between classes. It is also easier to locate the related classes. The package statement should be the first name in the file. Each source file can have only one package statement. If The package is not included, then the class, interface, enumerations, and annotation types will be put into an unnamed package.

You can declare package as :

package devmanuals;

Example :

class OverloadDemo {
	void test() {
		System.out.println("No parameters");
	}

	// Overload test for one integer parameter.
	void test(int a) {
		System.out.println("a:" + a);
	}

	// Overload test for two integer parameters
	void test(int a, int b) {
		System.out.println("a and b :" + a + " " + b);
	}
}

public class Overload {
	public static void main(String args[]) {
		OverloadDemo d = new OverloadDemo();
		d.test();
		d.test(10);
		d.test(10, 20);

	}
}

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>javac Overload.java

C:\Program Files\Java\jdk1.6.0_18\bin>java Overload
No parameters
a:10
a and b :10 20

Package Directory Structure

Points to remember if you are going to create a package :

  • The name of the package become the parts of the name of the class, after creating class inside package.

  • The name of the folder must be same as package.

  • If there is subpackage , then the subfolder must be of the same name as subpackage. For example, the path of the program given above should be :  ...../corejava/Overload

The import Keyword

For using another class of different package, first we need to make it available for class using 'import' keyword as :

import devmanuals.demo;

Here 'devmanuals' is package & the 'demo' is the name of the class.

After it , you  can use imported class in your class using full qualified name as :

devmanuals.Demo; 

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics