Guide To Package's in Java

Discussion in 'Java' started by techgeek.in, Mar 21, 2010.

  1. techgeek.in

    techgeek.in New Member

    Joined:
    Dec 20, 2009
    Messages:
    572
    Likes Received:
    19
    Trophy Points:
    0
    Occupation:
    EOC (exploitation of computers)..i m a Terminator.
    Location:
    Not an alien!! for sure
    Home Page:
    http://www.techgeek.in

    Introduction



    A package is a namespace that organizes a set of related classes and interfaces to provide access protection and namespace management.You can think of packages as being similar to different folders on your computer. Software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages. JDK has set of previously defined packages consisting of relevant classes.E.g IO package contains all the classes related to input output. Moreover, many times when we get a chance to work on a small project, one thing we intend to do is to put all java files into one single directory. It is quick, easy and harmless. However if our small project gets bigger, and the number of files is increasing, putting all these files into the same directory would be a nightmare for us. In java we can avoid this sort of problem by using Packages.

    Benefits:-

    • We can easily determine that the classes and interfaces in a single package are related.
    • The names of your classes and interfaces won't conflict with the names in other packages because the package creates a new namespace.
    • You can allow classes within the package to have unrestricted access to one another yet still restrict access for types outside the package.

    To create a package, you choose a name for the package and put a package statement with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package. If you do not use a package statement, your type ends up in an unnamed package (Use an unnamed package only for small or temporary applications).

    Syntax:

    package <packageName>;

    e.g:- package MyPackage;

    This should be the first statement of the source file before any imports and class declarations.

    Example:-


    Code:
    package MyPackage;
    class xx 
    {
           .
           .
    }
    class yy 
    {
    	public static void main(String args[]) 
       {
           .
           .
       }
    
    }
    
    then a directory called MyPackage should be created under the actual directory and the file should stay in that directory. When this particular file is saved it should be saved as yy.java within the directory MyPackage. So when it is compiled the .class files xx.class and yy.class are automatically going to stay in MyPackage directory.
    A Hierarchy of packages may be created. To do so, simply each package name should be separated from the one above it by use of a period.

    package pkg1[.pkg2[.pkg3]]];

    But it should also stay in the corresponding directory.

    For eg. a package declared as

    package java.awt.image
    should stay in

    java\awt\image directory.

    Now, again if a particular. java file is made to stay in a directory because it is written as a part of a corresponding package, then the file should be executed accordingly. For eg. the execution of yy.java in the earlier example should be done as
    java MyPackage.yy

    being in the actual directory i.e path just above the package.
    An Example:-

    Code:
    // A simple package
    package  MyPackage;
    class Balance 
           {
    		String name;
    		double bal;
    		Balance(String n, double b) 
                       {
    		name = n;
    		bal = b;
                       }
                   void show( ) 
                      {
    		if (bal < 0)
    			System.out.print(“--> ”);
    		System.out.println(name + “: $ ” + bal);
    	          }
          } 
    
    class AccountBalance 
          {
    	public static void main(String args[]) 
                      {
    		Balance current[] = new Balance[3];
    		current[0] = new Balance(“K. J. Fielding”, 123.23);
    		current[1] = new Balance(“Will Tell”, 157.02);
    		current[0] = new Balance(“Tom Jackson”, -12.33);
    		for (int i = 0; i < 3; i ++) current[i].show( );
    	         }
           }
    
    This file should be called AccountBalance.java and should be placed in a directory named MyPackage. Then after compilation the AccountBalance.class will stay in the MyPackage directory. However, if this does not happen by default then all the .class files should be placed in the MyPackage directory. Then the file should be executed by the command
    java MyPackage.AccountBalance

    Access Protection



    It is sure that if a particular variable is declared private then that variable could be accessed within that class only. It could not be accessed anywhere anyway outside that class. If a variable is made default(not declared public, private or protected) then the variable can be thought to be acting like a private variable outside the package i.e. outside the package that variable cannot be accessed neither from any subclass of that class nor from any other classes. In order to access that variable from outside the package, the variable has to be declared as public or protected. If it is public, then it can be accessed directly from any subclass of that class outside and through an object of that class from some other classes. However if the variable is declared as protected, then it can be accessed outside the package only from any subclass of that class. Moreover, a class has only two possible access levels:- default and public. When a class is declared as public, it is accessible by any other code. If a class has default access, then it can only be accessed by other code within its same package.
    Code:
    +--------------------------------+---------+-------------+-----------+--------+
    |                                | Private | No Modifier | Protected | Public |
    +--------------------------------+---------+-------------+-----------+--------+
    | Same class                     |  Yes    |  Yes        |  Yes      |  Yes   |
    | Same package subclass          |  No     |  Yes        |  Yes      |  Yes   |
    | Same package non-subclass      |  No     |  Yes        |  Yes      |  Yes   |
    | Different package subclass     |  No     |  No         |  Yes      |  Yes   |
    | Different package non-subclass |  No     |  No         |  Yes      |  Yes   |
    +--------------------------------+---------+-------------+-----------+--------+
    
    An Access Example:-
    Code:
    // file Protection.java
    
    package p1;
    public class Protection 
          {
    	int n = 1;
    	private int n_pri = 2;
    	protected int n_pro = 3;
    	public int n_pub = 4;
                 public Protection( ) 
                    {
    		System.out.println(“base constructor”);
    		System.out.println(“n = ” + n);
    		System.out.println(“n_pri = ” + n_pri);
    		System.out.println(“n_pro = ” + n_pro);
    		System.out.println(“n_pub = ” + n_pub);
    	        }
            }
    // file Derived.java
    
    package p1;
    class Derived extends Protection 
           {
    	Derived( ) 
                    {
    		System.out.println(“derived constructor”);
    		System.out.println(“n = ” + n);
    
    		// class only
    		// System.out.println(“n_pri = ” + n_pri);
    		System.out.println(“n_pro = ” + n_pro);
    		System.out.println(“n_pub = ” + n_pub);
    	         }
             }
    
    // file SamePackage.java
    
    package p1;
    class SamePackage 
             {
    	      SamePackage( ) 
                     {
    		Protection p = new Protection( );
    		System.out.println(“same package constructor”);
    		System.out.println(“n = ” + p.n);
    		// class only
    		// System.out.println(“n_pri = ” + p.n_pri);
    		System.out.println(“n_pro = ” + p.n_pro);
    		System.out.println(“n_pub = ” + p.n_pub);
    	          }
               }
    // file Protection2.java
    
    package p2;
    class Protection2 extends p1.Protection 
             {
     	       Protection2( ) 
                     {
    		System.out.println(“derived other package constructor”);
    		// class or package only
    		// System.out.println(“n = ” + n);
    		// class only
    		// System.out.println(“n_pri = ” + n_pri);
    		System.out.println(“n_pro = ” + n_pro);
    		System.out.println(“n_pub = ” + n_pub);
    	          }
               }
    // file OtherPackage.java
    
    package p2;
    class OtherPackage 
              {
    	       OtherPackage( ) 
                     {
    		p1.Protection p = new p1.Protection( );
    		System.out.println(“other package constructor”);
    		// class or package only
    		// System.out.println(“n = ” + p.n);
    		// class only
    		// System.out.println(“n_pri = ” + p.n_pri);
    		// class, subclass or package only
    		// System.out.println(“n_pro = ” + p.n_pro);
    		System.out.println(“n_pub = ” + p.n_pub);
    	          }
                }
    
    

    Using Classes From Other Packages



    To use a public package member (classes and interfaces) from outside its package, you must do one of the following
    • Import the package member using import statement
    • Import the member's entire package using import statement
    • Refer to the member by its fully qualified name (without using import statement).

    Importing Packages


    To be able to use classes outside of the package you are currently working in, you need to import the package of those classes. By default, all Java programs import the java.lang.* package, that is why you can use classes like String and Integers inside the program even though you haven't imported any packages.

    The syntax for importing packages is as follows:

    import <nameOfPackage>;

    Example:
    Importing a class
    import java.util.Date;

    Importing all classes in the java.util package
    import java.util.*;

    Using Classes of other packages via fully qualified path
    public static void main(String[] args)
    {
    java.util.Date x = new java.util.Date();
    }

    Example:-
    Code:
    //Thus file Protection2.java could have been:-
    
    
    package p2;
    import p1;
    class Protection2 extends Protection 
            {
    	  Protection2( ) 
                  {
    		System.out.println(“derived other package constructor”);
    		// class or package only
    		// System.out.println(“n = ” + n);
    		// class only
    		// System.out.println(“n_pri = ” + n_pri);
    		System.out.println(“n_pro = ” + n_pro);
    		System.out.println(“n_pub = ” + n_pub);
    	       }
             }
    
    Another example of import:-

    Code:
    package MyPackage;
    /* Now, the Balance class, its constructor, and its show( ) method are public. This means that they can be used by non-subclass code outside their packages. */
    public class Balance 
           {
    	String name;
    	double bal;
    	public Balance (String n, double b) 
                 {
    		name = n;
    		bal = b;
    	     }
    	public void show( ) 
                 {
    		if (bal < 0)
    			System.out.print(“-->”);
    		System.out.println(name + “: $” + bal);
    	     }
              }
    
    import MyPackage.*;
    class TestBalance 
             {
    	 public static void main(String args[]) 
                 {
                 /* Because Balance is public, the Balance class may be used and its          constructor may be called. */
                  Balance test = new Balance(“J. J. Jaspers”, 99.88);
                  test.show( );	// show( ) may also be called.
    	     }
               }
    
    

    Must Read Concept Of Package And ClassPath



    Suppose you have created a java file named "xyz.java" in "c:\" and inside that java file u have mentioned that the classes should belong to a package "techgeek".( package techgeek; ).
    Now under that condition if u compile the java file using command line like the following:-

    c:\javac xyz.java

    then .class file(s) are created in the same drive where the actual source file exists i.e source file and the corresponding class files exists side by side irrespective of the package definition inside the source file. As we know that for running that .class file containing "main" we need to have the path just before the package ( we know that package is nothing but a directory, so the path should be just above the package name). The program should be run like this:-

    c:\java techgeek.xyz;

    but after you type "enter" you will get an error msg because in actual the class file is itself located to "c:\" without creation of any package though the class file has compiled description of package which the class file belongs to. So how to run that file? you do one thing make a folder named "techgeek" in the "c:\" and place all the generated class files from the file "xyz.java" into that folder.Now you run the above command:

    c:\java techgeek.xyz

    Summary:-
    for any package based java program if you compile using command line then no package(directory) is created and all the class files are created beside the source file.Interesting thing is that the compiled class file has got the info of the package embedded. So while running that class file the concept of package is to be included. For this we need to create the directory hierarchy by ourselves and include all the class files there.

    Now,on the other hand, when you compile with the help of Jcreator then the Jcreator creates the package hierarchy from the path of the source file and include all the generated class files at the end of the hierarchy i.e if you consider the above example then while compiling the file "xyz.java" a new directory named "techgeek" is already created and all the class files is kept into that directory. So the users need not have to create the package manually.

    Now let me discuss the very important part of the package.Till now we know that how to include the package classes. This is done by using the keyword "import" e.g import java.io.*;

    But the million dollar question is how to import the classes residing in user defined package? Let me explain this to you. Suppose you created a class namely "abc.java" inside "c:/" and the class files should belong to "pack1" package. The scenario would be like this:-


    c:\-------> abc.java

    c:\------->pack1----->abc.class (or may be other classes)


    Now, again let us create an another java file namely "xyz.java" in "d:\".The class files should be under package "pack2.pack3"

    After compilation the situation would be like this:-

    d:\------>xyz.java
    d:\------>pack2---->pack3----->xyz.class(or may be other classes)



    Now, create an another source file namely "pqr.java" in "e:\".The class files should be under package "pack4.pack5.pack6" and the class files uses the object of the classes of "abc.java" and "xyz.java". (try to understand this)

    i.e the source code pqr.java contains the code like this:-

    import pack1.abc;

    import pack2.pack3.xyz;

    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    abc a=new abc();
    xyz x=new xyz();
    .
    .
    .



    now, the challenge is to compile the file "pqr.java" because all the above imported packages are user defined and jre has no idea about that.

    Actually this type of job is done by setting classpath. This can be done in three ways:-
    1. Using "set"

      e:/set classpath=.;c:/;d:/;
      e:/javac pqr.java


      after this the scenario would be like this:-

      e:\----->pqr.java
      e:\----->pack4---->pack5---->pack6---->pqr.class(or may be other relevant classes).


      now running the program:-

      e:/java pack4.pack5.pack6.pqr


      Note:- you might be wondering that why the class path is only restricted to c:/ in case of abc.java classes and d:/ in case of xyz.java classes.The reason is that the class path should only be mentioned till the path above the package. The package identification is give by "import" keyword itself.Every classpath is separated by ";" and the first "." represents the "current working directory" i.e it signifies that the classes that might be present in the current working directory should also be considered.The "." can be neglected.

      e:/set classpath=;c:/;d:/;

    2. mention the classpath at the time of compiling:-

      e:/javac -classpath (or -cp) ;c:/;d:/; pqr.java

      while running

      e:/java -classpath ;c:/;d:/; pack4.pack5.pack6.pqr

    3. In this method set the environment variable CLASSPATH by the following steps:-
      • right click on my computer to open the properties windows.
      • Goto "advanced" tab.
      • click on "environment variables" button.
      • under "system variables" create a new variable namely "classpath" and set its values as:-

      c:\;d:\;

      apply the changes

      now after doing all these compile like this

      e:\javac pqr.java


      run the program like this

      e:\java pack4.pack5.pack6.pqr
    [note:- The above concept is made easy as far as possible. :nice:)
     
    1 person likes this.
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
  3. SEOblue

    SEOblue New Member

    Joined:
    Apr 15, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://www.gigsport.com
    very informative..thanks
     
  4. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
  5. IBNSC

    IBNSC New Member

    Joined:
    Apr 24, 2010
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    thanks for you sharing ,I learn a lot thinks
     
  6. karthikeyan98

    karthikeyan98 New Member

    Joined:
    Dec 5, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    where will be the Java API packages stored like java.util*, java.lang.*
    how can i view those classes and make modification and recompile those.

    for example i need to modify the Runnable Interface how can i do so..
     
  7. sureshdsk

    sureshdsk New Member

    Joined:
    Jun 9, 2010
    Messages:
    7
    Likes Received:
    1
    Trophy Points:
    0
    can u tell me a package deals with time operations.................

    actually i want to show the remaining time to download the file in my DOWNLOAD MANAGER MINI PROJECT
     
  8. fashionbop

    fashionbop New Member

    Joined:
    Sep 11, 2009
    Messages:
    27
    Likes Received:
    1
    Trophy Points:
    0
    Occupation:
    Shopping from China
    Location:
    Guangzhou, China
    Home Page:
    http://www.fashion-bop.com
    Details decides success or failure! you are very imfomative!
     
  9. sbsl

    sbsl Banned

    Joined:
    Sep 20, 2011
    Messages:
    10
    Likes Received:
    0
    Trophy Points:
    0
    thanks for this information.....
     
  10. herandez21

    herandez21 New Member

    Joined:
    Dec 1, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    sales manager
    Location:
    united states
    Details decides success or failure! you are very imfomative!
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice