Java Subpackages: Hierarchical Organization Explained
Table of Content:
Package inside the package is known as subpackage. The packages that come lower in the naming hierarchy are called "sub package" of the corresponding package higher in the hierarchy i.e. the package that we are putting into another package is called "sub package".
The naming convention defines how to create a unique package name so that packages that are
widely used with unique namespaces. This allows packages to be easily managed. Suppose we
have a file called "HelloWorld.java
". and want to store it in a
sub package "subpackage", which stays inside
package "package1". The "HelloWorld
" class
should look something like this:
Program:
package package1.subpackage; public class HelloWorld { public void show(){ System.out.println("This is the function of the class HelloWorld!!"); } }
Now import the package "subpackage" in the class file "CallPackage" shown as:
import package1.subpackage.*; class CallPackage{ public static void main(String[] args){ HelloWorld h2=new HelloWorld(); h2.show(); } }
Output:
C:\atnyla\package1\subpackage\HelloWorld.java C:\atnyla\package1\subpackage>cd.. C:\atnyla\package1>cd.. C:\atnyla>javac CallPackage.java C:\nisha>java CallPackage This is the function of the class HelloWorld!!
How to send the class file to another directory or drive?
There is a scenario, I want to put the class file of A.java source file in classes folder of d: drive. For example:
//save as Simple.java package mypack; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to atnyla"); } }
To Compile:
e:\sources> javac -d d:\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=d:\classes;.; |
e:\sources> java mypack.Simple |
Another way to run this program by -classpath switch of java:
The -classpath switch can be used with javac and java tool.
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
Welcome to atnyla