What is package? How can we create your own packages? Explain.
Packages
- Java package is a mechanism of grouping similar type of classes, interfaces, and sub-classes collectively based on functionality. When software is written in the Java programming language, it can be composed of hundreds or even thousands of individual classes. It makes sense to keep things organized by placing related classes and interfaces into packages.
- A java package is a group of similar types of classes, interfaces, and sub-packages.
- Package in java can be categorized in two forms, built-in package, and user-defined package.
- There are many built-in packages such as java, lang, awt, java, swing, net, io, util, SQL, etc.
- Here, we will have the detailed learning of creating and using user-defined packages.
- Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations, and annotations easier, etc.
- A Package can be defined as a grouping of related types(classes, interfaces, enumerations annotations ) providing access protection and namespace management.
- Some of the existing packages in Java are:
java.lang=bundles the fundamental classes
java.io=classes for input, output functions are bundled in this package
Programmers can define their own packages to bundle groups of classes/interfaces, etc.
2nd part
When creating a package, you should choose a name for the package and put a package statement with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package. The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file. If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an unnamed package.
Example
package P1;
public class A
{
public void show()
{
System.out.printIn("From Class A of Package P1");
}
}
Compile the above file and put the file A. class in a sub-directory called P1. Now, we can use the above class from the different packages as below:
import P1.*;
public class B
{
public static void main(String a[])
{
A x=new A();
x.show();
}
}
Output:From Class A of Package P1
Comments
Post a Comment