A package is a folder, which is a collection of classes. It provides a convenient way to organize those classes. Each package consists of classes, interfaces as it's members.
Why Packages?
Classes with the same name cannot be created in the same directory. To overcome this problem, package is used. Thus, packages help to resolve name space conflict.
The general form of the package is,
package pkg1.pkg2;
For example,
package java.kalyan.kk;
status that the program is stored in a directory java\kalyan\kk.
How to create a Package?
The keyword package is used to create a package while creating the package the first statement in our program must be the package statement.
For example,
package arthemetic;
public class Operations
{
public float addition(float a,float b)
{
return(a+b);
}
public float subtraction(float a,float b)
{
return(a-b);
}
public float multiplication(float a,float b)
{
return(a*b);
}
public float division(float a,float b)
{
return(a/b);
}
}
The simple way to compile a package has to steps.
- Save the above program with class name "Operations".
- Then compile it with the command "javac -d . Operations.java".
Then it creates a Directory with the Package name (mypack) and save the created class file in mypack directory .
How to import a package?
If you want to use classes of one package in another classes in different package, then those classes can be access in your classes using import statement.
The general form of accessing a package is,
import package_name.class_name;
Explination: Here import is a keyword used to access a package. class_name is the name of class, another package we want to use to use package. The package_name is the name of the package which we want to access.
In addition to user-defined classes, Java provides thousands of Java classes are also available to users. Java classes are packages and are placed in the Java Development Kit (JDK) using import statement we can access them.
For example,
import java.io.*;
import java.awt.*;
Following program is an example program to demonstrate how to import a package...
import arthematic.Operations;
class ImportPack
{
public static void main(String args[])
{
Operations op=new Operations();
System.out.println(op.addition(2.5f,3.5f));
}
}
08:20
Share:
0 comments: