Packages form the basic building blocks of software components in many programming languages. For example, in Java you use the package statement to define the package for a class as follows.
package a.b;
public class C {
public static void main(String[] args) {
System.out.println(“hello world”);
}
}
The dot is used in package names to create sub-packages. However, in Java you have to create a directory tree to mirror your package hierarchy. So the file containing the example class C must be in a directory b that has a parent directory a. In the parent directory of a, you can start the compiler and interpreter as follows.
~/data/code/java/> javac a/b/C.java
~/data/code/java/> java a.b.C
hello world
Please note that you have to use slashes for the compiler and dots for the interpreter. Of course, an IDE takes care of this for you. Further information about Java packages can be found in the Java tutorial.
Python packages are somewhat similar to Java packages in that the package hierarchy is mirrored as a directory tree. But the package directories need special marker files __init__.py for Python to recognize them as package directories. So the following directory tree creates a simple package hierarchy.
a/
__init__.py
b/
__init__.py
c.py
The __init__.py files can be empty or contain package initialization code. If file c.py contains the following code
def main():
print “hello world”
you can use the function main() as follows
>>> import a.b.c
>>> a.b.c.main()
hello world
Further information about Python packages can be found in the Python tutorial.
In C# you don’t need to mirror your package hierarchy with directories. You just create a file wherever you want and use the namespace statement to create packages.
namespace a.b {
public class C {
static void Main() {
System.Console.WriteLine(“hello world”);
}
}
}
Again you can use the dot to create sub-packages. There’s no need to create a directory tree or take care of the package when compiling.
C:\Data\Code\C-Sharp\> csc c.cs
C:\Data\Code\C-Sharp\> c.exe
hello world
Further information about namespaces can be found at MSDN.
In Lisp, using packages is a bit different. First you define the package, then you change your current package to the defined package and then you define your functions or whatever you need in that package.
(defpackage :mhnfoo
(:use :common-lisp)
(:export #:printadd))
(in-package :mhnfoo)
(defun printadd (x y) (print (+ x y)))
This works when you save the commands in a file or in the REPL.
CL-USER> (mhnfoo:printadd 1 2)
3
3
Further information about packages can be found in the Common Lisp HyperSpec.