Java Packages, Package is a keyword, by using this keyword one can create another package. Following is an example where developer is going to create the Splesson package.
Simple.java
[java]package splesson;
public class Simple{
public static void main(String args[]){
System.out.println("Hello, Welcome to package");
}
} [/java]
With out any IDE package will be compiled as follows.
[java]javac -d . Simple.java
//The -d is a switch that tells the compiler where to put the class file i.e. it represents destination folder.[/java]
Code will be run as follows.
[java]java splesson.Simple[/java]
Output
Now compile the code result will be as follows.
[java]Hello, Welcome to package[/java]
By using three ways developer can access the Java Packages from another package, they are as follows.
- import package.*;
- import package.classname;
- fully qualified name.
Following is the structure to use packages.
By using import package.*;
Here developer is going create another package with the name
pack.
A.java
[java]package pack;
public class A{
public void msg(){
System.out.println("Welcome To Splessons");}
} [/java]
Now the developer is going to create main method in
splesson package with different class.
B.java
[java]package splesson;
import pack.*;//here used import keyword.
public class B {
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
[/java]
Here the developer user previous package by using
import keyword.
[java]import pack.*;[/java]
Output
When compile the code result will be as follows.
[java]
Welcome To Splessons
[/java]
By using import package.classname;
B.java
[java]package splesson;
import pack.A;
public class B {
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
[/java]
Where the developer used
import pack.A;
Output
When compile the code result will be as follows.
[java]
Welcome To Splessons
[/java]
B.java
[java]package splesson;
import pack.A;
public class B {
public static void main(String args[]){
pack.A obj = new pack.A();//fully qualified name.
obj.msg();
}
}
[/java]
Following is the fully qualified name.
[java]pack.A obj = new pack.A();[/java]
Output
When compile the code result will be as follows.
[java]
Welcome To Splessons
[/java]