Wednesday, September 28, 2016

Packages in Java

Packages:

Packages are nothing but folder structure, inside that we will create our java classes.
Classes with related functionality are bundle together in the same packages.
If you put all files of a project to a single package, it will be very difficult to manage the files.

Advantages of Packaging.
  • .       Better development and Organization of files:
Packaging helps to organize files in your project. You can arrange all Java classes with similar functionality to one folder.

E.g 1
          Java libraries are arranged in such way that , 
                           all I/O related functionality put inside  -> java.io package
                           Network related functionality put inside -> java.net
E.g
         If you are developing a shopping cart application we want different modules like
ProdcutDisplay, Promotions , ItemsPage, Checkout. 
So during development If we put each modules under each packages then it will be easy to develop and organize.

                  abc.shoppingCart. ProdcutDisplay
                  abc.shoppingCart. Promotions
                  abc.shoppingCart. Checkout

If 3 people are working on this project so that they can develop each module independently.
  • .       Resolve name conflict:

            Packaging helps to resolve name conflicts, if different packages have classes with same name.
Every class contained in a package has a unique name that cannot conflicts with class names defined in another packages.

E.g 
2 companies A & B are developing shopping cart application and they used identical name for their checkout classes.
If they have used the packaging then name conflict will not happen.

A. shoppingCart. Checkout
B. shoppingCart. Checkout

Creating Packages in Java Programs:

Package is creating in java with ‘package’ keyword , which is the first keyword in any java program followed by import statements.

package com.abc.shoppingcart;


If we want to use method of java classes you have to import that. Java.lang package in imported implicitly by default.

No comments:

Post a Comment