A package is a group of similar types of class, interfaces and sub-packages.
Package 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.
package in java :: futureX |
In this page, we will have the detailed learning of creating user-defined packages.
Advantage of Package
- Package is used to categorize the classes and interfaces so that they can be easily maintained.
- Package providEs access protection.
- Package removes naming collision.
Example
To compile : javac -d . Simple.java
To run : java mypack.Simple
package com;
class Simple{
public static void main(){
System.out.println("hello java");
}
}
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current folder.
How to access package from another package?
- import package.*;
- import package.classname;
- fully qualified name.
The import keyword is used to make the classes and interface of another package accessible to the current package.
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
If you import package.classname then only declared class of this package will be accessible but not subpackages.
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.
package math;
public class Calc{
public static int cube(int n){return n*n*n;}
}
//import all the classes of that package
package com;
import math.*;
class Simple{
public static void main(String args[]){
System.out.println(Calc.cube(5));
}
}
//only declared class is acessible
package com;
import math.Calc;
class Simple{
public static void main(String args[]){
System.out.println(Calc.cube(5));
}
}
//without import, full qualified name
package com;
class Simple{
public static void main(String args[]){
System.out.println(math.Calc.cube(5));
}
}
Subpackages:
Package inside the package is called the subpackage. It should be created to categorize the package further. Let's take an example, Sun Microsystems has defined 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.
standard declaration:
com.companyname.packagename.classname
package com.techshakti.math;
public class subpackage{
public static int cube(int n){return n*n*n;}
}
JAVA TUTORIALS HOMEPAGE