Java Package
Java Package
com
http://www.javatpoint.com/package
Java Package
next prev
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
System.out.println("Welcome to package");
5.
1/7
6. }
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current
package.
4. }
1. package mypack;
2. import pack.*;
3. class B{
2/7
4.
5.
6.
obj.msg();
7.
8. }
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
4. }
1. package mypack;
2. import pack.A;
3. class B{
4.
5.
6.
obj.msg();
7.
8. }
Output:Hello
4. }
1. package mypack;
2. class B{
3.
4.
5.
obj.msg();
3/7
6.
7. }
Output:Hello
Note: Sequence of the program must be package then import then class.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the package
further.
Let's take an example, Sun Microsystem has definded a package named java that contains many classes like
System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer
classes are for Input/Output operation, Socket and ServerSocket classes are for networking etc and so on. So,
Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the Input/Output
related classes in io package, Server and ServerSocket classes in net packages and so on.
4.
System.out.println("Hello subpackage");
5.
6. }
To Compile: javac -d . Simple.java
4/7
1. package mypack;
2. public class Simple{
3. public static void main(String args[]){
4.
System.out.println("Welcome to package");
5.
6. }
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the class file
resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
5/7
To run this program from e:\source directory, you can use -classpath switch of java that tells where to look for
class file. For example:
e:\sources> java -classpath c:\classes mypack.Simple
Output:Welcome to package
Rule: There can be only one public class in a java source file and it must be saved by
the public class name.
1. class A{}
2. class B{}
3. public class C{}
6/7
7/7