In this article we are going to describe what is package in Java and where its used and how we can use it. A Java package is similar to a namespace in C#.
IntroductionThis article describes what a package in Java is and where and how it is used. Packages are similar to namespaces in C#.
DefinitionA package is a grouping of related types providing access protection and namespace management. Note that types refer to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces.
Benefit of package
Thus we can say that
Some core packages of Java are:
Create It's Own packageFor creating a package we use the following steps.Defining a PackageTo define a package, include a package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package. If you omit the package statement then the class names are put into the default package, that has no name. This is the general form of the package statement:
Syntax
package packageName;How to create a hierarchy of packagesTo create a hierarchy of packages, separate each package name from the one above it with a period. The general form of a multilevel package statement:
package pkg1[.pkg2[.pkg3]];ExampleIn this example we create a folder named Package and save this Java file with the name OwnPackage.java. The package name and folder name should be the same:OwnPackage.java
package Package;
public class OwnPackage
{
public static void main(String args[])
System.out.println("this Example of creating own package");
System.out.println("Myself Abhishek dubey");
System.out.println("you can put n number of class in your package");
System.out.println("this is enough to under stand package");
}
}OUTPUT After running this code the output wil be as follows:
How to Use package For using the Java core packages we import the packages and for importing we use the import statement. In a Java source file, import statements occur immediately following the package statement and before class definitions.This is the general form of the import statement:Syntax
import pkg1[.pkg2].(classname.*);(*) means including all classes under that package.For exampleimport java.lang.*;ExampleIn this example we are going to import the util package to use the class, as in:
import java.util.Date;
public class PackageDemo {
public static void main(String arg[])
System.out.println(new Date());
System.out.println("My self Abhishek dubey");
System.out.println("Its example How we import java package");
OutputAfter running the preceding application we'll find the following output:
Solutions Manual to Objects First with Java – A Practical Introduction using BlueJ