CSC 207 Algorithms and Object-Oriented Design

Weiss, from section 3.8 to the end of chapter 3 (pages 90–107) Packages

• A package consists of a set of classes. • Think of a package as a folder on your . – Word documents in one folder – Images in another folder • Store related classes in a separate package. • Java provides a library of classes (bundled into packages) for use in our applications. – Application Programming Interface (API) https://docs.oracle.com/javase/8/docs/api/index.html

Package

• Find classes easier • Provide access visibility for class and its members • Avoids naming conflicts – Two classes with the same name are members of different packages. Package Statement • Create a package . Put package name at the top of Java source files  Only one package statement for a given file . Place source file in an appropriate (sub)directory . Package names are spelled out in lower case.

Switch.java package utilities; public class Switch{ …}  : utilities.Switch Package Members

• Access package members – Fully qualified name – Import package member – Import the entire package of member Access Package Members • Fully qualified name (suitable for infrequent use) public class SwitchTester { utilities.Switch s = new utilities.Switch(); } • Access a specific member import utilities.Switch; public class SwitchTester { Switch s = new Switch(); } • Access all members import utilities.*; public class SwitchTester { SwitchOne s = new SwitchOne(); SwitchTwo t = new SwitchTwo(); } Package Name Hierarchy

• Java package names may be hierarchical – They contain periods for separating different parts of a package e.g., ch03.stacks • Package files must be placed underneath a set of subdirectories that match the separate parts of the package name. – Files are inside stacks directory that is a subdirectory of ch03 directory • Import the entire package to your program – import ch03.stacks.*; CLASSPATH • Consider this import statement in a Java file: import ch03.stacks.*;

• Compiler finds the package if the directory that contains ch03 directory is on CLASSPATH of a computer.  CLASSPATH contains paths to directories. The paths are separated by colons.

• Compiler searches for all CLASSPATH directories to find ch03/stacks/ • Set CLASSPATH on UNIX CLASSPATH=CLASSPATH:$HOME/ADT/ export CLASSPATH Package Visibility

• If a class field or method does not have a visibility modifier, the field is package visible. – The field or method can be accessed only by classes in the same package. • Package visibility also applies to classes. – A package-visible class is only accessible to classes inside the same package.