Java Packages
Java Packages
ON
JAVA PACKAGES
CONTENTS
Introduction
Types Of Packages
System Packages or Java API
Accessing a Package
o Advantages Of Packages
INTRODUCTION
In java, programmers can create several classes &
Interface. After creating these classes and interface, it
is better if they are divided into some groups
depending on their relationship. Thus, the classes
and interface which handle similar or same task are
put into the same directory or folder, which is also
known as package.
We must first declare the name of the package using the package
keyword followed by the package name. This must be the first
statement in a Java source file. Then define a classes as normally as
define a class.
Example :
package myPackage;
public class class1
{
------------ -
// Body of class1
}
The .class files 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 that will import the package are located.
STEPS FOR CREATING PACKAGE :
To create a user defined package the following steps
should be involved :-
1: Declare the package at the beginning of a file using
the syntax :-
package packageName;
2: Define the class that is to be put in the package &
declare it public.
3: Create a subdirectory under the directory where the
main source files are stored.
4: Store the listing as the classname.java file in the
subdirectory created.
5: Compile the file. This create .class file in the
subdirectory.
STEPS FOR CREATING PACKAGE :
To create a user defined package the following steps
should be involved :-
1: Declare the package at the beginning of a file using
the syntax :-
package packageName;
2: Define the class that is to be put in the package &
declare it public.
3: Create a subdirectory under the directory where the
main source files are stored.
4: Store the listing as the classname.java file in the
subdirectory created.
5: Compile the file. This create .class file in the
subdirectory.
Java also supports the concept of package hierarchy. This
is done by specifying multiple names in a package
statement, seprated by dots (.).
Ex :- package firstPackage.secondPackage;
This approach allows us to group related classes into a
package and their group related package into a larger
package. Store this package in a subdirectory named
firstpackage/secondPackage.
A java package file can have more than one class
definition. In such cases, only one of the classes may be
declared public & that class name with .java extension is
the source file name. When a source file with more than
one class definition is compiled, java creates independent
.class files for those classes.
ACCESSING A PACKAGE
Java package can be accessed either using a fully qualified
class name or using a shortcut approach through the import
statement.
Syntax :
import package1[.package2][.package3].classname;