Packages From Deitel Deitel Packages A package is

  • Slides: 6
Download presentation
Packages From Deitel & Deitel

Packages From Deitel & Deitel

Packages • A package is a group of related classes • All of the

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

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: Time 1. java from Deitel and Deitel package com. deitel.

// Fig. 8. 1: Time 1. java from Deitel and Deitel package com. deitel. jhtp 7. ch 08; public class Time 1 { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 public void set. Time( int h, int m, int s ) { // method contents not shown } // end method set. Time // convert to String in universal-time format (HH: MM: SS) public String to. Universal. String() { return String. format( "%02 d: %02 d", hour, minute, second ); } // end method to. Universal. String // convert to String in standard-time format (H: MM: SS AM or PM) public String to. String() { return "this is an example"; } // end method to. String } // end class Time 1

Declarations and Packages • Order of declarations – package declaration – if any –

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

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.