Introduction to Programming Languages/Scoping with Namespaces

Namespaces are named program regions used to limit the scope of variables inside the program. They are used in many programming languages to create a separate region for a group of variables, functions, classes, etc. The usage of namespaces helps to avoid conflict with the existing definitions. Namespaces provide a way of implementing information hiding. Some examples of namespaces in Java are classes and packages. Examples of namespaces in C++ are classes, namespaces, and struct. The source code bellow illustrates the usage of namespace in Java:

The Java code above defines a namespace called geometry. This definition provides a way of discriminating the class  from others that could be defined by other programmers. This discrimination is performed because the defined namespace is incorporated to the class. So, the class becomes. The first line of the code shows an import statement, which is the way Java shares definitions. It is interesting to note that the method  uses the definition   from the imported namespace.

In  language, the   keyword is used to create namespaces. The  statement is a way of sharing definition in C++. The next example illustrates the definition of two namespaces ( and  ) and their use. Namespaces are usable by taking their name reference with scope resolution operator (operator "::"). This is illustrated in the statement  at line 14. Namespaces are also used with the  keyword, which makes all the members of the namespace available in the current program and the members can be used directly, without taking reference of the namespace. The statement present in the line 3 of the code makes the  object available in the function   without the usage of the scope resolution operator.

The keywords  and , which will be better detailed in other section of this wikibook, modify the visibility of the definitions in a namespace. There is no difference between a class and a struct in a  program, except that by default, the members of a struct are public, and the members of a class are private. Also structs are by default inherited publicly and classes by default are inherited privately. Other than that, whatever you can do in a class, you can do in a struct.

Language library is a collection of definitions and implementations that provide ready-to-use functions. They are a way to grow a programming language. In a C++ program, a library can be included using using the  directive. The previous  example used this construct in the line 1 to include the   library.