Package in Java
Package in Java
Package in Java
Java Package
MainFile.java MainFile.java
project 3
Package
In a project, there are many files, some files for GUI, some files for Database
connectivity, some files for for network connections handling.
4
Package
Package are used in java to avoid name conflict and control access.
5
Let’s say one java file stored in project directory. Name of file is webserver.java.
Now another programmer in same project wants to create same name file.
If he will try to save his file with same name then there will be an error.
6
One way he can save his file is by making one more directory inside project and then
save the file inside new directory jack.
7
Package
Project
webserver.java
jack
webserver.java
8
How to create package?
1. package jack;
2. Class webserver
3. {
4. public static void main(String arg[])
5. {
6. System.out.println(“This is web server”);
7. }
8. }
First line is for package specification, in which package current file will be stored.
9
Advantage of Java Package
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to access package from another package?
• import package.*;
• import package.classname;
• fully qualified name.
1) Using packagename.*
• //save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
• //save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
2) Using packagename.classname
• //save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
• //save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
3) Using fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
• //save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
“ If you import a package, sub packages will
not be imported.”
Subpackage in java
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}