Monday, February 19, 2018

Java Packages


https://docs.oracle.com/javase/tutorial/java/package/packages.html
https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html

Creating and Using Packages

To make types easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups of related types into packages.


package is a grouping of related types providing access protection and name space management. 

Note that types refers to classes, interfaces, enumerations, and annotation types. 

Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces.





Creating a Package


The package statement (for example, package graphics;) must be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.


Note: If you put multiple types in a single source file, only one can be public, and it must have the same name as the source file. For example, you can define public class Circle in the file Circle.java, define public interface Draggable in the file Draggable.java, define public enum Day in the file Day.java, and so forth.

You can include non-public types in the same file as a public type (this is strongly discouraged, unless the non-public types are small and closely related to the public type), but only the public type will be accessible from outside of the package. All the top-level, non-public types will be package private.



If you do not use a package statement, your type ends up in an unnamed package. Generally speaking, an unnamed package is only for small or temporary applications or when you are just beginning the development process. Otherwise, classes and interfaces belong in named package.



Naming a Package

With programmers worldwide writing classes and interfaces using the Java programming language, it is likely that many programmers will use the same name for different types. 

In fact, the previous example does just that: It defines a Rectangle class when there is already a Rectangle class in the java.awt package. Still, the compiler allows both classes to have the same name if they are in different packages. The fully qualified name of each Rectangle class includes the package name. That is, the fully qualified name of the Rectangle class in the graphics package is graphics.Rectangle, and the fully qualified name of the Rectangle class in the java.awt package is java.awt.Rectangle.

This works well unless two independent programmers use the same name for their packages. What prevents this problem? Convention.

Naming Conventions

Package names are written in all lower case to avoid conflict with the names of classes or interfaces.

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.

Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).

Packages in the Java language itself begin with java. or javax.

In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int"

In this event, the suggested convention is to add an underscore. For example:

Legalizing Package Names
Domain NamePackage Name Prefix
hyphenated-name.example.orgorg.example.hyphenated_name
example.intint_.example
123name.example.comcom.example._123name



Using Package Members

The types that comprise a package are known as the package members.
To use a public package member from outside its package, you must do one of the following:
  • Refer to the member by its fully qualified name
  • Import the package member
  • Import the member's entire package



Importing a Package Member

import graphics.Rectangle;
Rectangle myRectangle = new Rectangle();

Importing an Entire Package

import graphics.*;
Circle myCircle = new Circle();
Rectangle myRectangle = new Rectangle();

The asterisk (*) in the import statement can be used only to specify all the classes within a package

Note: Another, less common form of import allows you to import the public nested classes of an enclosing class. For example, if the graphics.Rectangle class contained useful nested classes, such as Rectangle.DoubleWide and Rectangle.Square, you could import Rectangle and its nested classes by using the following two statements.

import graphics.Rectangle;
import graphics.Rectangle.*;   // this do not import Rectangle, only import nested classes

Be aware that the second import statement will not import Rectangle



Apparent Hierarchies of Packages

Importing java.awt.* imports all of the types in the java.awt package, but it does not import java.awt.colorjava.awt.font, or any other java.awt.xxxx packages. If you plan to use the classes and other types in java.awt.color as well as those in java.awt, you must import both packages with all their files:

import java.awt.*;    // import types only, not packages
import java.awt.color.*;


Name Ambiguities

Use the member's fully qualified name to indicate exactly which Rectangle class you want.

Rectangle rect;
graphics.Rectangle rect;

The Static Import Statement

The static members of Math can be imported either individually:

import static java.lang.Math.PI

Now we can use PI directly instead of using Math.PI

import a group:

import static java.lang.Math.*;

Note: Use static import very sparingly. Overusing static import can result in code that is difficult to read and maintain, because readers of the code won't know which class defines a particular static object. Used properly, static import makes code more readable by removing class name repetition



Managing Source and Class Files

Many implementations of the Java platform rely on hierarchical file systems to manage source and class files.


The qualified name of the package member and the path name to the file are parallel, assuming the Microsoft Windows file name separator backslash (for UNIX, use the forward slash).
  • class name – graphics.Rectangle
  • pathname to file – graphics\Rectangle.java
As you should recall, by convention a company uses its reversed Internet domain name for its package names. 


The full path to the classes directory, <path_two>\classes, is called the class path, and is set with the CLASSPATH system variable. 
Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path.

For example, if

<path_two>\classes

is your class path, and the package name is

com.example.graphics,

then the compiler and JVM look for .class files in

<path_two>\classes\com\example\graphics.


A class path may include several paths, separated by a semicolon (Windows) or colon (UNIX).

By default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in your class path.


Setting the CLASSPATH System Variable

To display the current CLASSPATH variable, use these commands in Windows and UNIX (Bourne shell):

In Windows:   C:\> set CLASSPATH
In UNIX:      % echo $CLASSPATH

To delete the current contents of the CLASSPATH variable, use these commands:

In Windows:   C:\> set CLASSPATH=
In UNIX:      % unset CLASSPATH; export CLASSPATH

To set the CLASSPATH variable, use these commands (for example):

In Windows:   C:\> set CLASSPATH=C:\users\george\java\classes
In UNIX:      % CLASSPATH=/home/george/java/classes; export CLASSPATH



Summary of Creating and Using Packages

To create a package for a type, put a package statement as the first statement in the source file that contains the type (class, interface, enumeration, or annotation type).

To use a public type that's in a different package, you have three choices: 
  1.  use the fully qualified name of the type, 
  2.  import the type,
  3.  import the entire package of which the type is a member.


The path names for a package's source and class files mirror the name of the package.

You might have to set your CLASSPATH so that the compiler and the JVM can find the .class files for your types.


QUIZ


Question 1: Assume that you have written some classes. Belatedly, you decide that they should be split into three packages, as listed in the table below. Furthermore, assume that the classes are currently in the default package (they have no package statements).

Package NameClass Name
mygame.serverServer
mygame.sharedUtilities
mygame.clientClient

a. What line of code will you need to add to each source file to put each class in the right package?
Answer 1a: The first line of each file must specify the package:
In Client.java add:
package mygame.client;
In Server.java add:
package mygame.server;:
In Utilities.java add:
package mygame.shared;
b. To adhere to the directory structure, you will need to create some subdirectories in your development directory, and put source files in the correct subdirectories. What subdirectories must you create? Which subdirectory does each source file go in?

Answer 1b: Within the mygame directory, you need to create three subdirectories: clientserver, and shared.
In mygame/client/ place:
Client.java
In mygame/server/ place:
Server.java
In mygame/shared/ place:
Utilities.java
c. Do you think you'll need to make any other changes to the source files to make them compile correctly? If so, what?

Answer 1c: Yes, you need to add import statements. Client.java and Server.java need to import the Utilities class, which they can do in one of two ways:
import mygame.shared.*;
       --or--
import mygame.shared.Utilities;
Also, Server.java needs to import the Client class:
import mygame.client.Client;






No comments:

Post a Comment

java special for collection size, array size, and string size

Size: For Collections (eg: Map, List, etc ): usually it use collection.size(), eg         Map<Character, Integer> map ...