import Declarations


import Declarations

When a class or interface has been placed in a package, it is identified by its fully qualified name , the package and class names together. For instance, the Species class described in the previous section would be referred to as the Fluids.Gas.Species class. You can well imagine that this situation becomes quite cumbersome if intricate package hierarchies are involved.

You can avoid having to use the fully qualified name of a package member by placing an import declaration at the beginning of your source code, below any package declarations. The import declaration does not load anything into the code. It simply allows you to use the unqualified or simple name for one or more package members . There are two ways to use the import declaration ”to access a single class or interface type and to refer to any member of a single package by its unique name.

To access a single class or interface type, enter the fully qualified name of the member after the import keyword. For example, to import the Species class from the Fluids.Gas package you would type

 import Fluids.Gas.Species; 

To refer to any member of a single package by its unqualified name, place an asterisk after the package name. To import the contents of the Fluids.Gas package you would type

 import Fluids.Gas.*; 

One thing to be aware of is that the wildcard character * will only import all the types defined in a single package, not an entire package hierarchy.

Example: Importing a User-Defined Package

The SpeciesDriver class creates a Species object and an IonizedSpecies object. To refer to these classes by their simple names, an import declaration is placed at the beginning of the source code. To get this example to work, the Fluids.Gas package path will need to be part of the CLASSPATH environment variable described in the next section.

 import Fluids.Gas.*; public class SpeciesDriver {   public static void main(String args[]) {     //  Create Species and IonizedSpecies objects     Species n = new Species("atomic nitrogen", 0.0140067);     IonizedSpecies o2p =             new IonizedSpecies(                  "diatomic oxygen ion", 0.03199825, 1);     //  Print out some information about the objects     System.out.println("molar mass of " +            n.getName() + " is " + n.getMolarMass());     System.out.println("molar mass of " +            o2p.getName() + " is " + o2p.getMolarMass());     System.out.println("charge level of " +            o2p.getName() + " is " + o2p.getChargeLevel());    } } 

Output ”

 molar mass of atomic nitrogen is 0.0140067 molar mass of diatomic oxygen ion is 0.03199825 charge level of diatomic oxygen ion is 1 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net