Search This Blog

Monday 28 November 2016

Packages in Java

Use of packages in Java

Packages in Java helps resolve naming conflicts,  when your project have classes with the same names.
Java Packages helps you organize class files within your project.
If we to put all .java files into a single package,then it become a nightmare to manage all your files as the project gets bigger.
You can create a package with package keyword, which is the first keyword in any Java program
followed by import statements.
The java.lang package is imported implicitly by default and all the other packages must be explicitly imported.
package com.package01.util ;
java.io.BufferedReader;
import java.util.Date;

A package in Java is an encapsulation mechanism that can be used to group related classes, interfaces, and subpackages.
The dot (.) notation is used to uniquely identify package members in the package hierarchy. 
The class java.sql.Date is different from the class java.util.Date. The MyClass class can be easily identified by the name com.mypackage.MyClass. This is called the fully qualified name of the package member. 
It is not surprising that most Java programming environments map the fully qualified name of packages on the underlying (hierarchical) file system.
Defining Packages: A class or interface can indicate that its Java byte code be placed in a particular package, using a package declaration. 
The package statement has the following syntax: 
package <fully qualified package name>;
At most one package declaration can appear in a source file, and it must be the first statement in the unit.
If a package declaration is omitted in a compilation unit, the Java byte code for the declarations in the compilation unit will belong to an unnamed package, which is typically synonymous with the current working directory on the host system.

Using Packages
Given a reference type that is accessible from outside a package, the reference type can be accessed in two ways. 
  • The first form uses the fully qualified name of the type. However, writing long names can become tedious. 
  • The second form uses the import declaration to provide a shorthand notation for specifying the name of the type. 
The import declarations must be the first statement after any package declaration in a source file. The simple form of the import declaration has the following syntax: 
import <fully qualified type name>; or 
import <fully qualified package name>.*;
An import declaration does not recursively import subpackages. 


2 comments:

  1. Nice blog...
    You can also visit for more information:

    https://wingsofm.blogspot.in

    ReplyDelete
    Replies
    1. Nice blog...
      You can also visit for more information:

      https://wingsofm.blogspot.in

      Delete