Organize Code

Namespace

Java

 

Defining Namespace

Java 8
package myproject;

public class Greeting {
  public void greet() {
    System.out.println("Hi!");
  }
}

Namespaces are to avoid conflicting definitions and introduce more flexibility and organization in the codebase.

Namespacing in Java is done using Packages.

Package definition should be the first thing in the file.

 

Namespace Hierarchy

Java 8
// myproject/Greeting.java file
package myproject;

public class Greeting {
  public void greet() {
    System.out.println("Hi!");
  }
}

// myproject/english/Greeting.java file
package myproject.english;

public class Greeting {
  public void greet() {
    System.out.println("Hello!");
  }
}

// myproject/spanish/Greeting.java file
package myproject.spanish;

public class Greeting {
  public void greet() {
    System.out.println("Hola!");
  }
}

Java namespaces can have hierarchical structure, much like directories and files in the file system.

The convension is to have nested directories with a same names for each Package reflecting the package hierarchy.

Here we have 3 files including a same class name Greeting, each in its own package.

 

Namespace direct access

Java 8
myproject.spanish.Greeting g = 
  new myproject.spanish.Greeting();

g.greet();   // Hola!

Packages items can be accessed directly using their fully-qualified-name.

For example here we are directly pointing to Greeting class inside myproject.spanish package.

 

Importing

Java 8
import myproject.english.Greeting;

public class App {
  public static void main(String[] args)
  {
    Greeting g = new Greeting();
    g.greet();   // Hello!
  }
}

Java supports wildcards in imports as well as single item imports. So you can do:

import myproject.*;

This will import all classes and interfaces from myproject package but not from subpackages like myproject.english.