Packages in Java
Packages in Java
● A package in java is a container for the class that is used to keep the class name space
compartmentalized. Here we organize files into different directories according to their
functionality. Packages are collection of classes and interfaces to facilitate a number of
readymade solutions.
● It allows flexibility to give same name to many classes, that is to avoid name space
collision
● It provides mechanism for partitioning the class name space into more manageable
chunks.
● It supports reusability and maintainability
● Access limitation can be applied with the help of packages.
● Nesting of package is possible.
✔ Packages are two types . Build in packages(java API packages) and user
defined.
Creating a user defined package
1. Use package statement at the beginning of the package file.
2. Define the class that is to be put in the package and declare it as public.
3. Create subdirectory under the working directory with the same name as the package
name.
4. Store the file with the same name as the className.java in the subdirectory created
5. Store the compiled version file(i.e .class) into the same sub-directory
Defining a package:
package <package name>;
public class <class name>
{…………….
……………..
}
4. Compile B.java file. This will create a B.class file and place it in the directory
p1.
Example:
package myPack;
public class Balance
{
String name;
double bal;
public Balance(String n, double b)
{
name=n;
bal=b;
}
public void show()
{
System.out.println(name+","+bal);
}}
Adding more classes to a Package :
We can add more classes to a created package by using package name at the top of the program and
saving it in the package directory. We need a new java file to define a public class, otherwise we can
add the new class to an existing .java file and recompile it.
Accessing classes inside a package
Consider following two statements :mport the Vector class from util package.
Example:
package myPackage;
System.out.println(s);
}}
import myPackage.MyClass;
// with a value
// the package.
obj.getNames(name);
Note : MyClass.java must be saved inside the myPackage directory since it is a part of the package.