Java Package
In this chapter you will learn:
- What is Java package
- How to define a Java package
- How to create a hierarchy of packages
- How to map Java package to directory
Description
Packages are containers for classes. Packages are used to keep the class name space compartmentalized. In Java, package is mapped to a folder on your hard drive.
Syntax
To 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, the class names are put into the default package, which has no name.This is the general form of the package statement:
package packageName;
Create a hierarchy of packages
To create a hierarchy of packages, separate each package name from the one above it by use of a period. The general form of a multileveled package statement:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development system.
Java package maps to directory
Java package maps to physical directory on your hard drive. As what is defined in the following example, you have to save the following file to a file named Main.java and create a folder named MyPack to actually store Main.java file.
package MyPack;//from w w w. j av a 2 s .c o m
public class Main {
public static void main(String args[]) {
System.out.println("hi");
}
}
Then try executing the class, using the following command line:
Next chapter...
What you will learn in the next chapter:
- How to write import statement
- Syntax for Java Packages Import
- What is static import and how to use static import
Java Object
Java Object Reference Variable
Java Methods
Java Method Return
Java Method Parameters
Java Class Constructors
Java Default Constructor
Java Constructor Parameters
Java this Keyword
Java static keyword
Java Method Overload
Java Constructors Overload
Java Method Argument Passing
Java Method Recursion
Java Nested Class
Java Anonymous Classes
Java Local Classes
Java Member Classes
Java Static Member Classes
Java Class Variables
Java main() Method
Java Class Inheritance
Java super keyword
Java Method Overriding
Java Constructor in hierarchy
Polymorphism
Java final keyword
Java Abstract class
Java Class Access Control
Java Package
Java Packages ImportJava Interface
Java Interface as data type
Java interface as build block
Java instanceof operator
Java Source Files