Namespaces help in organizing the code and create globally distinct types to avoid naming
collisions in a project.
Namespaces are more useful in large projects to avoid name collisions and provide clear
separation of modules.
Without using the namespace, we cannot have duplicate class names or cannot use the same class
again in the project files. If any duplicate class exists then the compiler throws a compilation
issue as the class name already used or defined.
But in real-time we may need to use the same class name for different modules and it is possible with the help of namespaces of having the same
classes in different modules by keeping under the namespaces.
To understand the need for having the same classes or naming collision:
let’s understand an example of a banking project where it has customers having saving
account and current account.
Under saving account there is a customer class and
operative methods in customer class and similarly under current account there is a
customer and methods in the customer class. So to separate the modules and use the
customer class names in each module, keep a customer class under SavingsAccount
namespace and keep another customer class under CurrentAccount namespace and access
those classes with namespace.classname (SavingsAccount.Customer or
CurrentAccount.Customer)
Syntax: It uses a namespace keyword
namespace
{
//code here..
}
Example 1: The same Greet classes still be used in a project by using Namespace avoid naming collision.
The output will be: