Packages

Figure 217. Why packages ? Slide presentation Create comment in forum
  • Grouping of related classes (e.g. subsystems).

  • Structuring big systems.

  • Provide access restrictions.

    public, private and protected modifier

  • Resolving class name clashes. Example:

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


Figure 218. Rules and conventions Slide presentation Create comment in forum
  • 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 219. Qualified name vs. import Slide presentation Create comment in forum
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 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 220. Don't be too lazy! Slide presentation Create comment in forum
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 221. Classes from package java.lang Slide presentation Create comment in forum
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 222. Class, package and file system Slide presentation Create comment in forum
Class, package and file system

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

Generated byte code in corresponding directory hierarchy.


Figure 223. Source hierarchy view Slide presentation Create comment in forum
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.