Next: , Previous: Basic concepts, Up: About CNI


11.2 Packages

The only global names in Java are class names, and packages. A package can contain zero or more classes, and also zero or more sub-packages. Every class belongs to either an unnamed package or a package that has a hierarchical and globally unique name.

A Java package is mapped to a C++ namespace. The Java class java.lang.String is in the package java.lang, which is a sub-package of java. The C++ equivalent is the class java::lang::String, which is in the namespace java::lang which is in the namespace java.

Here is how you could express this:

     (// Declare the class(es), possibly in a header file:
     namespace java {
       namespace lang {
         class Object;
         class String;
         ...
       }
     }
     
     class java::lang::String : public java::lang::Object
     {
       ...
     };

The gcjh tool automatically generates the necessary namespace declarations.

11.2.1 Leaving out package names

Always using the fully-qualified name of a java class can be tiresomely verbose. Using the full qualified name also ties the code to a single package making code changes necessary should the class move from one package to another. The Java package declaration specifies that the following class declarations are in the named package, without having to explicitly name the full package qualifiers. The package declaration can be followed by zero or more import declarations, which allows either a single class or all the classes in a package to be named by a simple identifier. C++ provides something similar with the using declaration and directive.

In Java:

     import package-name.class-name;

allows the program text to refer to class-name as a shorthand for the fully qualified name: package-name.class-name.

To achieve the same effect C++, you have to do this:

     using package-name::class-name;

Java can also cause imports on demand, like this:

     import package-name.*;

Doing this allows any class from the package package-name to be referred to only by its class-name within the program text.

The same effect can be achieved in C++ like this:

     using namespace package-name;