Wednesday, February 23, 2011

What is a Package?

Packages are namespaces that organize a group of related classes and interfaces. Packages can be thought as folders on your computer system. Many projects might contain html pages in one folder, images in another, scripts, interfaces and so on. Normally, a real world software written in Java contains hundreds or even thousands of Java classes, so it makes sense to keep all these files organized by placing related files into packages. Packages make easier to find related files and use them. As well packages are helpful because they avoid naming conflicts and facilitate control access.

Typical project structure using packages in Eclipse

The previous image depicts a project called Restaurant with 3 different packages: restaurant.api, restaurant.lib and test. And within the packages a set of related classes. One common example of packages can be found in the Java platform itself. In it, classes are included on various packages that bundle classes by function: fundamental classes are in java.lang, classes for reading and writing (I/O) are in java.io and so forth.

Suppose you write a group of classes that represent graphic objects, such as circles, rectangles, lines, and points. You also write an interface, Draggable, that classes implement if they can be dragged with the mouse.

//in the Draggable.java file
package graphics;
public interface Draggable {
. . .
}

//in the Graphic.java file
package graphics;
public abstract class Graphic {
. . .
}

//in the Circle.java file
package graphics;
public class Circle extends Graphic implements Draggable {
. . .
}

//in the Rectangle.java file
package graphics;
public class Rectangle extends Graphic implements Draggable {
. . .
}

//in the Point.java file
package graphics;
public class Point extends Graphic implements Draggable {
. . .
}

//in the Line.java file
package graphics;
public class Line extends Graphic implements Draggable {
. . .
}

Some of the advantages programmers can get by bundling related classes and interfaces in a package include the following :

  • You and other programmers can easily determine that these types(classes & interfaces) are related.

  • You and other programmers know where to find types that can provide graphics-related functions.

  • The names of your types won't conflict with the type names in other packages because the package creates a new namespace.

  • You can allow types within the package to have unrestricted access to one another yet still restrict access for types outside the package.

No comments:

Post a Comment