Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Packages and the import Statement

Up until now, you have been using the fully qualified name of the class java.util.ArrayList. The fully qualified name of a class includes its package name (java.util in this example) followed by the class name (ArrayList).

Packages provide a way for developers to group related classes. They can serve several needs: First, grouping classes into packages can make it considerably easier on developers, saving them from having to navigate dozens, hundreds, or even thousands of classes at a time. Second, classes can be grouped into packages for distribution purposes, perhaps to allow easier reuse of modules or subsystems of code.

Third, packages provide namespaces in Java. Suppose you have built a class called Student and you purchase a third-party API to handle billing students for tuition. If the third-party software contains a class also named Student, any references to Student will be ambiguous. Packages provide a way to give a class a more unique name, minimizing the potential for class name conflicts. Your class might have a fully qualified name of com.mycompany.studentinfosystem.Student, and the third-party API might use the name com.thirdpartyco.expensivepackage.Student.

I will usually refer to the Java system classes without the package name unless the package is not clear from the class name. For example, I will use ArrayList in place of java.util.ArrayList, and Object instead of java.lang.Object.

Typing java.util.ArrayList throughout code can begin to get tedious, and it clutters the code as well. Java provides a keyword—import—that allows identification of fully qualified class names and/or packages at the source file level. Use of import statements allows you to specify simple class names throughout the remainder of the source file.

Update CourseSessionTest to include import statements as the very first lines in the source file. You can now shorten the phrase extends junit.framework.TestCase to extends TestCase. You can change the reference defined as java.util.ArrayList<Student> to ArrayList<Student>.


   import junit.framework.TestCase;

   import java.util.ArrayList;

public class CourseSessionTest extends TestCase {
   ...
   public void testEnrollStudents() {
      CourseSession session = new CourseSession("ENGL", "101");

      Student student1 = new Student("Cain DiVoe");
      session.enroll(student1);
      assertEquals(1, session.getNumberOfStudents());
      ArrayList<Student> allStudents = session.getAllStudents();
      ...
   }
}

(Make sure your tests still run! I'll keep reminding you for a while.)

Update AllTests, StudentTest, and CourseSession to use import statements. Your code will look so much cleaner!

  • + Share This
  • 🔖 Save To Your Account