Learn Package In Java Fast and Easy Manner

digitization, transformation, binary

Package In Java

Hide the implementation: Package concept

One of the main features 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 won’t have to rewrite code if a new version of the 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. So this feature allows us to use the code without physically copying them into the program(under development).

Ads code goes here

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. Packages can be considered as a 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 created 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 the same name as the public class.

If there are many classes in .java files, those many .class files will be created. These .class files are packaged together with the 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 code by subclassing 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 the same name. They should be referred by their fully qualified name along with package and class name.
  • The 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.
  • packages give better classification.
  • packages give better naming conflict resolution.
  • packages give visibility control.

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 these 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 the 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 the import keyword, we can tell the 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.

READ  Learn String Class in Java Quick in 20 Minutes

If we have packages, they must be the first part of Java non-comment statements. The import statement allows us to refer to classes by abbreviated names. The import must appear after the package statement.

A single package cannot have two different classes with the same name. A top-level package is only accessible outside the package if it is public default package is called an unnamed package. Import package is a convenient way to not to write the same code again.

Example:

package com.techtravelhub;
import java.awt.*;

How package solve namespace or name collision issue

The reason for the 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 the 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.

As my domain name is techtravelhub.in, then the utility library and ReadFile class will be com.techtravelhub.Utility.ReadFile path where dot(.) stands for subdirectories. 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 a unique identifier(class names within a file must be unique).

How to create our 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 the 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.Colour;
  2. Use import every class contained in the specified package. Like-java.aw.*;

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

How to access user-defined packages:

For accessing user-defined packages below are the rules:

  1. Using the 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 the import statement to make the name or names available for use.


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 namespace 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 subdirectory of the directory where classes will import package are located.
    • The 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 set up 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=javaclasses;javaprojectpackages;
     

Popular Packages in java:

PackageComments
java.lang.*The java language package provides the classes and interfaces that form the 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 provide the generic data structure
(Dictionary,Hashtable,Stack,Vectors),String manipulation(String tokenizer),calendar,date utilities.Interfaces like-observer
an 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 the Abstract Window Toolkit. It also has two more subclasses.
java.awt.imageThis package contains classes and interfaces for performing sophisticated image producing. This is needed to create or manipulate
image and colours
java.awt.peerThis 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.
READ  Class Random in Java

Packages naming convention

Packages name uses standard java naming rules. By convention, packages begin with a lower case letter and class name starts with an 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 a prefix to the preferred package is followed.

Package creation guidelines

  • The 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 subdirectory under the directory where the main source files are stored.
  •  Store the listing as the classname.java file in the subdirectory created.
  • Compile the files. This will create the .class files in the subdirectory.

The subdirectory name must match the package name exactly.Java supports the concept of package hierarchy. This is done by specifying multiple names in a package statement, 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 be cluttered. To prevent this we place all the .class files for a particular package into a single directory. It is a 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 the same, in that case, it will tough to use them. To support this we need to write an Internet-friendly naming convention. But the 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 have 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 besides, 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 techtravelhub.com so the package will be com.techtravelhub, so say oracle.com the package will be com.oracle)If we follow this conversion, we will never face-name clash. What if we do not have our 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 machine. So when the java program is running, it needs to load the .class file. (Maybe dynamical, 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 an 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 fooabcmnoxyz 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.

READ  List Concept Simplified In Java

An Example:


package IN.MydigitalVoice.util;
 

this package name can be used as an umbrella namespace 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 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 subdirectory on our system like-


c:DOCJavaMyProgramInMyDigitalVoiceUtil
 

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:javalib;C:DOCJavaMyProgram
 

The CLASSPATH can contain another 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 the compiler encounters the import statement, it begins searching at the directory specified by the CLASSPATH looking for a subdirectory INMyDigitalVoiceUtil.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 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 the 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 an xyz object like zyz x1, the compiler will not be able to understand which xyz class to take or use. In such case 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:

package abc;
public class B
{
//..body of class B
}
 
  1. Store this as B.java under directory packageName or abc.
  2. 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 a subdirectory 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 subdirectory created earlier and compile each source file, which completed, the package would contain .class files of all the source file.

 

Hiding of classes:

When we import packages using asterisks(*) all public classes of the package are imported. If we want to 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.

Class versus package:-

Class and package both signify for encapsulation and they both contain namespace and scope of variables and method. Class is a container for data and method code but package acts as a container for classes and other packages. Class is the smallest unit of abstraction.

Java resolves the visibility issues in the following manner-

  • Visibility within the class
  • Visibility in a subclass in the same package
  • Visibility in non-subclass in the same package.
  • Visibility in subclasses in different packages.
  • Visibility in subclasses that are neither in the same package nor are subclass.

 

Share and Enjoy !

Leave a Comment

Your email address will not be published. Required fields are marked *