JAVA | Explain package creation with suitable example.

Java provides a mechanism for partitioning the class namespace into more manageable parts called package (i.e. package are container for a classes). The package is both naming and visibility controlled mechanism. Package can be created by including package as the first statement in java source code. Any classes declared within that file will belong to the specified package. 

Syntax: package pkg; 
Here, pkg is the name of the package

example: package mypack;

Java uses file system directories to store packages. The class files of any classes which are declared in a package must be stored in a directory which has same name as package name. The directory must match with the package name exactly. A hierarchy can be created by separating package name and sub
package name by a period(.) as pkg1.pkg2.pkg3; which requires a directory structure as pkg1\pkg2\pkg3.
The classes and methods of a package must be public. To access package In a Java source file, import statements occur immediately following the package statement (if it exists) and before any class definitions. 

Syntax: 
import pkg1[.pkg2].(classname|*);

Example:
package1:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
System.out.println("Volume is:"+(l*b*h));
}
}
}
Source file:
import package1.Box;
class VolumeDemo
{
public static void main(String args[])
{
Box b=new Box(); b.display();
}
}

Post a Comment

0 Comments