Thursday, December 19, 2013

Use package members in Java

Summarize what is at http://docs.oracle.com/javase/tutorial/java/package/usepkgs.html to make it simple.

Referring to a Package Member by Its Qualified Name
eg: 
   graphics.Rectangle myRect = new graphics.Rectangle();

Importing a Package Member
eg: 
   import graphics.Rectangle;
   Rectangle myRectangle = new Rectangle();

Importing an Entire Package
eg: 
   import graphics.*;
   Rectangle myRectangle = new Rectangle();

Apparent Hierarchies of Packages
At first, packages appear to be hierarchical, but they are not.
eg:
  java.awt package,
  java.awt.color package,
  java.awt.font package,
   and many others that begin with java.awt.xxxx

However, the java.awt.color package, the java.awt.font package, and other java.awt.xxxx packages are not included in the java.awt package.

The prefix java.awt (the Java Abstract Window Toolkit) is used for a number of related packages to make the relationship evident, but not to show inclusion.


Name Ambiguities
Have to use the member's fully qualified name to indicate which you want.
eg: 
    pkgA.Rectangle rect1;
    pkgB.Rectangle rect2;

The Static Import Statement
Wen to access to static final fields (constants) and static methods from classes, the static import statement gives you a way to import the constants and static methods that you want to use so that you do not need to prefix the name of their class. In short, it's to make static stuff of a class available, it's kind of away from package include we are talking about above.
eg:
   import static java.lang.Math.PI;   //Math is a class & we use its static stuff.
       or as a group:
   import static java.lang.Math.*;

   double r = cos(PI * theta);     // cos() and PI are static stuff of class Math. 




No comments:

Post a Comment