Packages

Figure 192. Why packages ? Slide presentation
  • Grouping of related classes (e.g. subsystems).

  • Structuring big systems.

  • Provide access restrictions using:

    public, private and protected modifier

  • Resolving class name clashes. Example:

    java.lang.String vs. my.personal.String


Figure 193. Rules and conventions Slide presentation
  • Package names below java. are reserved.

  • Package names should not start with javax. either.

  • Package names must not contain operators:

    mi.hdm-stuttgart.de --> de.hdm_stuttgart.mi.

  • Packages should start with reversed DNS avoiding clashes.


Figure 194. Fully qualified class name vs. import Slide presentation
Fully qualified class name:
java.util.Scanner  scanner =          // Clumsy and
   new java.util.Scanner (System.in); // redundant
Using import:
import java.util.Scanner; 

public class Q {

  public static void main(String[] args) {
     Scanner  scanner = new Scanner (System.in);
       ...
  }
}
Fully qualified class name Using import

Using the fully qualified class i.e. including its package name name for defining a variable.

Creating an instance by using the fully qualified class name again.

Importing the Scanner class once.

Unqualified class use due to import.


Figure 195. Don't be too lazy! Slide presentation
Bad Good
import java.util.*;

public class Q {
  public static void
        main(String[] args) {
    Scanner s = 
      new Scanner(System.in);
    Date today = new Date();
  }
}
import java.util.Scanner;
import java.util.Date;

public class Q {
  public static void
         main(String[] args) {
    Scanner s =
       new Scanner(System.in);
    Date today = new Date();
  }
}

Figure 196. Special: Classes in package java.lang Slide presentation
import java.lang.String;   // Optional
import java.util.Scanner;  // Required
public class Q {

  public static void main(String[] args) {
    String message = "Hello!";
    Scanner  s = new Scanner(System.in);
  }
}

Classes belonging to the java.lang package are being imported automatically.

The Scanner class belongs to the java.util package and must thus be imported.

Without the import java.util.Scanner statement we need the fully qualified class name:

java.util.Scanner s = new java.util.Scanner(System.in);

Figure 197. Class, package and file system Slide presentation
Class, package and file system

A class Print defined in package my.first.javapackage.

Generated byte code in corresponding directory hierarchy.


Figure 198. Source hierarchy view Slide presentation
Source hierarchy view
package my.first.javapackage;
        ❷ ❸     ❹
public class Print { 
              ❺
  ...


}

Our project's start folder containing Java classes.

First package name component.

Second package name component.

Third package name component.

Class Print being contained within our package.