Package Concept Simplified In Java



Hide the implementation: Package concept
Java provides an opportunity to separate the things that change from the  things that stay the same. For example a Library,the client who is using it should be able to rely on the part they are using and know that they wan't have to rewrite code if a new version of library comes out.The library creator must have the freedom to make modification and improvements with utmost care so that the client programmer's code won't be affected by those changes.
The common conventions are:

  • The library programmer must agree not to remove existing methods when modifying a class in the library,as it may break the client code.
  • The library creator can not revamp the entire package or library.
To avoid the issue regarding this java provides access specifier to allow the library creator to specify something is available for consumers and remaining are not.Java does that by access specifiers.(public protected,private etc). This concept will ensure that all internal methods and data are private and only some method and data are exposed to the consumer.To understand it better lets us understand the .class file creation from a class. There can be only one public class in each compilation unit. When we compile a .java file,we get a .class file with same name as the public class. If there are many classes in a .java files, those many .class files will be created.These .class files are packaged together with linker to create an executable file.A working program is a bunch of .class files compressed in a jar.Java interpreter is responsible for finding ,loading and interpreting these files.There is nothing in java that forces the use of an interpreter. There exist native code , that produces a single executable file.A library is also a bunch of class files.Each file has one class that is public and there is one component for each file.
Advantages of Package

  • Ability to reuse a code by sub classing existing classes (by inheritance)
  • Collection of related classes(audio,video,text,graphics,project etc)
  • Make a structure that is compartmentalized.()
Import statement
In java we use import statement or keyword to bring in an entire library.The compiler will use this import statements to locate the actual class or where it is defined.

import java.util.*;
//.* will wildcard the package name and includes all packages under util.
import java.util.Vector
//Specify the full name only that particular class from the util package will be imported
 
How package solve namespace or name collision issue
The reason for import statement is to provide a mechanism to manage 'namespace'.Say classA has a foo() method and another class ClassB also has a foo() method. By the above way we can resolve the name collision and namespace.If there is any name collision like same class name is located under x and y both packages,in that case we have to use import x.nameoftheclass or y.nameoftheclass to use respective class
How to create our own package

package MyPackage;//package declaration 
public class MyClass{//class definition 
public void test(){
System.out.println("Welcome to my class");
}
}
 
Once saved in MyClasss.Java,it will be located in a directory named MyPackage. After compilation,we will get MyClass.class file in the same directory.We are indicating the compiler unit that MyPackage library will also be part of the compilation unit.That is teh public class name within this compilation unit is under the umbrella of the name-MyPackage.If anyone wants to use the name,they will either have to fully specify the name or use the import statement in combination with MyPackage.If the name of the file is MyClass.java,this means there can be one and only one public class in that file. The name of that class must be in MyClass.

How to access:
If anyone wants to use MyClass(any public class in the MyPackage),they must use import statement to make the name or names available for using.

import MyPackage.MyClass;
class PackageTest{
public static void main(String args[])
{
MyClass mc=new MyClass();
mc.test();
}
}
 
Alternatively we need to give fully qualified name-

MyPackage.MyClass m=new MyPackage.MyClass();
 
The package and import statements allow us to divide up. This single global name space so that no name clashing will occur(No matter how many people get on the internet and start creating classes in java).
Common Guidelines:

  • .class file must be located in a directory that has the same name as the package,this directory should be a sub directory of the directory where classes will import package are located.
  • Exact location of the package should be mentioned in the package statement.One can specify the directory hierarchy like package MyProject.Test.GUITest;
  • The directory in which the package is stored should be under the directory where java application want   to share the package classes
  • Java <---------------------------------working directory
    |
    |
    |
    |
    V
    .package MyProject.Test.GUI.class
    .MyPackage

    <---------------------------------package directory
    |
    |
    |
    |
    V
    .MyClass.java
    .Myclass.class
  • The best approach is to setup the system variable in CLASSPATH.The specific location that java compiler will consider as the root of any package hierarchy. This is also controlled.
    
    SET CLASSPATH=java\classes;java\project\packages;
     
Popular Packages in java:


Package Comments
java.lang.* The java language package provides the classes and interfaces that form core of java language and JVM.
It provides support for classes,objects,String,thread exceptions and wrapper classes.
It got imported automatically into every java program.  
java.io.* This package provides a set of I/O streams used to read and write files to I/O sources.
They are byte oriented and the classes defined here can be chained to implement more sophisticated stream functionalities.
java.utility.* This package contains a collection of utility classes and related interfaces.It provides classes that provides generic data structure
(Dictionary,Hashtable,Stack,Vectors),String manipulation(String tokenizer),calander,date utilities.Interfaces like-observer
observable class which allow objects to notify one another when they change.
java.net.* This package contains networking classes and interfaces,including classes that represent a URL and URL connection.Socket
connection and a class that represents Internet address.
java.awt.* This package provides standard graphical user interface elements(Button,List,Menus etc) with  containers(Window,Frame,MenuBar).
It also provides higher level dialogs. It supports Abstract Window Toolkit.It also has two more sub classes.
java.awt.image This package contains classes and interfaces for performing sophisticated image producing.This is needed to create or manipulate
image and colors
java.awt.peer This package contains interfaces used to connect AWT components to their windows,Systems specific implementations.(Motif widget)
Unless we are creating a window specific or system specific implementation,we need not use this interface.
Package creation guidelines

  • Package is never gets packaged into a single file.
  • Package contains many .class files.
These two concepts may have destroyed concept as files may cluttered.To prevent this we place all the .class files for a particular package into a single directory.It is bit logical too.This follows the hierarchical file structure of the operating system.This way of packaging resolves the problem of class  clutter. By using packages,we can resolve the namespace and name collision. But if the package names are same,in that case it will tough to use them. To support this we need to write Internet friendly naming convention. But issue with this approach is that it may download the classes automatically without the knowledge of the user.
So still there are two issues:
  1. Creating unique package names
  2. Finding the classes(may be buried in the directory structure)
To resolve these issues,Java developers has provided the below solutions:

  • To encode the path of the creation of the .class file into the name of the package(The compiler will enforce this).But in addition,by connection with the first part of the package name is the internet domain name of the creator of this class in reversed order.Since Internet domain names are generally to be unique(like mydigitalvoice.in so the package will be in.mydigitalvoice,so say oracle.com the package will be com.oracle)If we follow this conversion,we will never face nameclash. What if we do not have our own domain name? Well in that case use surname,name etc to make it unique.
  • The second part of the trick is resolving the package name into a directory on our own machine. So when the java program is running,it needs to load the .class file.(May be dynamically,where it needs to create an object of that particular class),It can locate the directory where the .class files reside. 
How Java Interpreter works for packages
It finds the environment variable CLASSPATH(set via operating system where java CLASSPATH contains one or more directories that may be used as a root for a search for .class files.)Starting at the root,the interpreter will take the package name and replace each dot with a slash to generate a path name from CLASSPATH root. So package foo.abc.mno.xyz will become foo\abc\mno\xyz or foo/abc/mno/xyz depending on the operating system.This is then concatenated to the various entries in the CLASSPATH. That's where it looks for the .class file with the name corresponding to the class, we are trying to create.
An Example:

package IN.MydigitalVoice.util;
 
this package name can be used as an umbrella name space for the following two files:

package IN.MydigitalVoice.util;
public class Vector{
public Vector()
{
system.out.println("Vector from mydigitalvoice");
}
}
 
Now when we try to create our own package-

package IN.MydigitalVoice.util;
public class List{
public List(){
system.out.println("List from mydigitalvoice");
}
}
 
Since we have given first non comment code,both of these files are placed in the sub directory on our system like-

c:\DOC\Java\MyProgram\In\MyDigitalVoice\Util
 
if the package name is In.MyDigitalVoice.Util but the first portion of the path comes from CLASSPATH environment variable,which is written

CLASSPATH=%*%,.;D:\java\lib;C:\DOC\Java\MyProgram
 
The CLASSPATH can contain other alternative search path also. The following code can be placed in any directory-

import IN.MyDigitalVoice.Util.*;
public class LibTest{
public static void main(String args[])
{
Vector v=new Vector();
List l=new List();
}
}
 
When compiler encounters the import statement, it begin searching at the directory specified by the CLASSPATH looking for a sub directory IN\MyDigitalVoice\Util.Then search the compiled files of the appropriate names(Vector.class and List.class for Vector and list respectively). Note both the classes are desired methods in the respective class must be public.
Package Concept Simplified In Java Package Concept Simplified In Java Reviewed by Animesh Chatterjee on November 08, 2018 Rating: 5

No comments:

Powered by Blogger.