Java Package
A java package is a group of similar types of classes,
interfaces and sub-packages.
Package in java can be categorized in two
form, built-in package and user-defined package.
There are many built-in packages such as
java, lang, awt, javax, swing, net, io, util, sql etc.
Package in Java is a mechanism to
encapsulate a group of classes, sub packages and interfaces.
Packages are used for:
·
Preventing
naming conflicts. For example there can be two classes with name Employee in
two packages, college.staff.cse.Employee and college.staff.ee.Employee
· Making
searching/locating and usage of classes, interfaces, enumerations and
annotations easier
·
Providing
controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its
subclasses. A default member (without any access specifier) is accessible by
classes in the same package only.
·
Packages
can be considered as data encapsulation (or data-hiding).
Fig: Java Package |
Advantage of Java Package
1) Java package is used to categorize the
classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Simple example of java package
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
syntax –
javac -d directory javafilename
Example-
javac -d . Simple.java
How to run java package program
You need to use fully qualified name e.g.
mypack.Simple etc to run the class.
To
Compile: javac
-d . Simple.java
|
To
Run: java mypack.Simple
Output: Welcome to packageAdding a class to a Package :We can add more classes to a created package by using package name at thetop of the program and saving it in the package directory. We need a newjava file to define a public class, otherwise we can add the new class to
an existing .java file and
recompile it.
Subpackages:Packages that are inside another package are the subpackages.These are not imported by default, they have to imported explicitly. Also,members of a subpackage have no access privileges, i.e., they are considered
as different
package for protected and default access specifiers.
|
Program:-
util is a subpackage created inside java package.
//
Java program to demonstrate accessing of members when
//
corresponding classes are imported and not imported.
import
java.util.Vector;
public
class ImportDemo
{
public
ImportDemo()
{
// java.util.Vector is imported, hence
we are
// able to access directly in our
code.
Vector newVector = new Vector();
// java.util.ArrayList is not
imported, hence
// we were referring to it using the
complete
// package.
java.util.ArrayList newList = new
java.util.ArrayList();
}
public
static void main(String arg[])
{
new ImportDemo();
}
}
Fig: Predefined package |
No comments:
Post a Comment