Package Concept Simplified In Java


Package Concept in java
Package Concept in java

Package Concept Simplified In Java

Hide the implementation: Package concept

One of the main feature of Object Oriented Programming is its ability to reuse the code that is already created as part of other source file.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.Sp this feature allows us to use the code without physically copying them into the program(under development).
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.
Packages are ways to group varieties of classes or interfaces together.Packages can be considered as container for classes.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.

Packages are therefore classified into two types:

  • Java standard API packages(Example-java.lang,java.Util,java.io,java.awt,java.net etc)
  • User defined packages

Advantages of Package

  • Ability to reuse a code by sub classing existing classes (by inheritance).The classes contained in the packages of their program can be easily reused.
  • Collection of related classes(audio,video,text,graphics,project etc)
  • Make a structure that is compartmentalized.()
  • In a single package the classes are unique.But two classes of two packages can have same name.They should be refereed by their fully qualified name along with package and class name.
  • Package provides a way to hide classes thus preventing other programs or package from accessing classes that are meant for internal use only.
  • Packages also provide a way for separating "design" from "coding".First we can design the classes and decide their relationship and then we can implement java code needed for the methods.It is also possible to change the implementation of any method without affecting the rest of the design. 

Import statement

When we want to use a predefined class in our code,the compiler must know how to locate it.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.

Case-I:

The class may exist in the same source code file that is being called from.Java eliminated the forward referencing problem,so we can use the class even if the class is not defined until later.

Case-II:

If the class exist in some other file.Java compiler has to feed the path of the specific class that we want to access.This is necessary as same class name may appear in different files.

import java.util.Vector
//Specify the full name only that particular class from the util package will be imported
import java.util.*;
//.* will wildcard the package name and includes all packages under util.

 
By using import keyword,we can tell compiler to bring in a package which is a library of classes.In the above example we are telling the compiler that we want to use java's vector class from the utility package.Now if we want to use multiple classes of the util package, we can use the second example.

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.Java supports an unambiguous name for a library,the specifier used is like internet domain in reverse order as those arguments are unique in nature.

As my domain name is mydigitalvoice.in ,then the utility  library and ReadFile class will be IN.mydigitalvoice.Utility.ReadFile path where dot(.) stands for sub directories.In general COM is used instead of in. Capitalized COM or IN is by convention.

This mechanism means that all our files automatically live in their namespace and each class within a file automatically has an unique identifier(class names within a file must be unique).

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 System packages:

There are two ways to access the System packages:

  1. Use the fully qualified class name of the class like-java.awt.Color;
  2. Use import every class contained in the specified package. Like-java.aw.*;

The packages within the package or the classes is represented by separating the levels with dot.

How to access user defined packages:

For accessing user defined packages below are the rules:

  1. Using fully qualified class name
  2. Using a shortcut approach through the import statement.
The major drawback of the shortcut approach is that it is difficult to determine from which package,a particular class is coming.This is very true and evident when a large number of packages are imported.But the advantage is that we do not need to use long package name again and again in the program.
The general form of import statement is as follows:

import package1[.package2][.package3]......[.packageN].className;
//package1 is the top level package
//or
import package1.*;
 
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:

The source file and the compiled file should be saved in the directory of which the named package is a subdirectory.
  • .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.

Packages naming convention

Packages name uses standard java naming rules.By convention,packages begin with a lower case letter and class name starts with a upper case letter.
Exp:
double y=java.lang.Math.sqrt(x);
Where:
lang is the package name starts with lower case
Math is the class name starts with Upper case
sqrt() is the method name , starts with lower case.
Every package name must be unique during run time. We will get run time exceptions/errors otherwise.Since all over the world java coders are coding,duplication may occurs.Java designers have recognized the problem and suggested a package naming convention that ensures the uniqueness.As per convention use of domain name as prefix to the preferred package is followed.

Package creation guidelines


  • Package is never gets packaged into a single file.
  • Package contains many .class files.
  • Declare the package name at the beginning of a file using the form-package packageName;
  • Define the class that is to be put in the package and declare it as public.
  • Create a sub directory under the directory where the main source files are stored.
  •  Store the listing as the classname.java file in the sub directory created.
  • Compile the files.This will create the .class files in the sub directory.
The sub directory name must match the package name exactly.Java supports the concept of package hierarchy.This si done by specifying multiple names in a package statements,separated by dots.(.)
like-package firstPackage.secondPackage;
This approach allows us to group related to classes into a package and then group related package into a large package.
A java package file can have more than one class definitions.In such cases,only one of the classes may be declared public and that class name with a .java extension is the source file name.When a source file with more than one class definition is completed,java creates independent class files for the classes we have defined.
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.

Automatic Compilation:

The first time we create an object of an imported class,the compiler will go hunting for the .class file of the same name(say we are creating an object of class x,it looks for x.class) in the appropriate directory.If it finds the x.class,that is what it must use.However it it also finds x.java at the same directory,the compiler will first compare the date stamp on the two files and if x.java is more recent than x.class,it will automatically recompile x.java to generate an up to date x.class.
When we import multiple packages,in such case,two or more packages contain classes with same name.

package pack1;
public class abc{}
public class xyz{}
package pack2;
public class xyz{}
public class pqr{}
//now if we want to import both packages using wild card syntax (.*)
import pack1.*;
import pack2.*;
 
and try to create a xyz object like zyz x1, the compiler will not be able to understand which xyz class to take or use. In such case in order to avoid compilation issue,we have to be more explicit about which one we intend to use like-

pack1.xyz x1;
pack2.xyz x2;
 
It is also possible to subclass a class that has been imported from another package.

import package2.classB
class classC extends classB {
.....
}
 

How to add a class to a package:

Steps are as follows:

  1. Define the class and make it public.
  2. Place the package statement in the class like package &lt;&lt;packageName&gt;&gt;
  3. put the class definition as follows:
  4. 
    package abc;
    public class B
    {
    //..body of class B
    }
     
  5. Store this as B.java under directory packageName or abc.
  6. Compile B.java to get the B.class file. Place this under abc directory.
In the same way we can add non public classes to the directory or package.
As java source file can have only one class declared as public , we can not put two or more public classes together in a .java file.This is because of the restriction that the file name should be same as the name of the public class with .java extension.

If we want to create a package with multiple public classes in it, we need to follow the following steps:

  1. Decide the name of the package
  2. Create sub directory with this name under the directory where main source files are stored.
  3. Create classes that are to be placed in the package in separate source files and declare the package statement at the top of each source file.
  4. switch to sub directory created earlier and compile each sourcefile,which completed,the package would contain .class files of all the sourcefile. 

Hiding of classes:

When we import packages using asterics(*) all public classes of the package are imported.If we want do not want any classes to be hidden or not allowed others to import,we may remove the public modifier.

package p1:
public class x{
{
...
//body of x
}
class y
{
//body of y
...
}
 
In this example class x is public hence available in outside but y is not hence not available.
Likewise we can add many non public classes as hidden.

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.