Difference between namespace in C# and package in Java

What is the difference (in terms of use) between namespaces in C# and packages in Java?


Solution 1:

From: http://www.javacamp.org/javavscsharp/namespace.html


Java

Packages are used to organize files or public types to avoid type conflicts. Package constructs can be mapped to a file system.

system.security.cryptography.AsymmetricAlgorithm aa;

may be replaced:

import system.security.Crypography; 
class xxx { ...
AsymmetricAlgorithm aa;

There is no alias for packages. You have to use import statement or fully-qualified name to mention the specific type.

package n1.n2;
    class A {}
    class B {}

or

package n1.n2;
   class A {}

Another source file:

package n1.n2;
   class B {}

Package cannot be nested. One source file can only have one package statement.

C#

Namespaces are used to organize programs, both as an "internal" organization system for a program, and as an "external" organization system.

System.Security.Cryptography.AsymmetricAlgorithm aa;

may be replaced:

using System.Security.Crypography; 
AsymmetricAlgorithm aa;

Alternatively, one could specify an alias for the the namespace, eg

using myAlias = System.Security.Crypography; 

and then refer to the class with

myAlias.AsymmetricAlgorithm 

namespace N1.N2
{
    class A {}
    class B {}
}

or

namespace N1
{
    namespace N2
    {
        class A {}
        class B {}
    }
}

Solution 2:

There are a few details that differ.

In Java the directory structure should match the package structure. No such restriction in C#.

In C# you can have multiple namespaces in one file. In Java one file belongs to one package (see previous).

Java has default/package accessibility. C# internal accessibility goes in assemblies.

If you use VS and Eclipse and let them structure the project, then you will not feel the differences much.

Solution 3:

There's no such term as "namespace" in Java - a package acts as a namespace in Java though, in terms of providing a scope for names. It's also part of the accessibility model.

From section 7 of the Java Language Specification:

Programs are organized as sets of packages. Each package has its own set of names for types, which helps to prevent name conflicts. A top level type is accessible (§6.6) outside the package that declares it only if the type is declared public.

EDIT: Okay, after the clarification: a Java package is similar to a C# namespace - except that it has an impact on accessibility, whereas in C# namespaces and accessibility are entirely orthogonal.

Solution 4:

In C++/C#, namespaces are just used for partitioning names to avoid collisions by accidentally using the same name for a variable in different places.

In Java, packages are far more than just that - packages are used for modules, the naming aspect is just a part of it.