Packages From Deitel & Deitel
Packages A package is a group of related classes All of the classes in the Java API are organized into classes.
Creating packages Before a class can be imported into multiple applications, it must be placed in a package to make it reusable Steps Make your class public Choose a unique package name Add a package declaration to the source code file. Note that there can be only one package declaration in each Java source-code file. The package declaration must precede all other declarations and statements in the file. Compile the class – so that it is placed in the appropriate package directory structure Import the reusable class into a program and use the class.
// Fig. 8. 1: Time1. java from Deitel and Deitel package com. deitel // Fig. 8.1: Time1.java from Deitel and Deitel package com.deitel.jhtp7.ch08; public class Time1 { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 public void setTime( int h, int m, int s ) { // method contents not shown } // end method setTime // convert to String in universal-time format (HH:MM:SS) public String toUniversalString() { return String.format( "%02d:%02d:%02d", hour, minute, second ); } // end method toUniversalString // convert to String in standard-time format (H:MM:SS AM or PM) public String toString() { return "this is an example"; } // end method toString } // end class Time1
Declarations and Packages Order of declarations package declaration – if any import declarations – if any class declarations Only one of the class declarations in a single file can be public. Other classes in the file are placed in the package and can be used only by the other classes in the package Non-public classes in a package are there to support the reusable classes in the package. Convention for naming package Domain name backwards (i.e. edu.jmu)
Getting to packages Use import statements Remember IF you use a wildcard to import all of the classes in a package, do not also import individual classes in the package Using the wildcard import statement does not affect the performance or the size of your program.