Java Packages
Java Packages & API
A package in Java is used to group related classes.
Think of it as a folder in a file directory.
We use packages to avoid name conflicts, and to write
a better maintainable code.
Packages are divided into two categories:
Built-in Packages (packages from the Java API)
User-defined Packages (create your own packages)
Built-in Packages
The Java API is a library of prewritten classes, that are free to use,
included in the Java Development Environment.
import package.name.Class; // Import a single class import
package.name.*; // Import the whole package
Import a Class
import java.util.Scanner;
Import a Package
import java.util.*;
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
String userName = myObj.nextLine();
System.out.println("Username is: " + userName);
}
}
User-defined Packages
package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
To create a package, use the package keyword.
C:\Users\Your Name>javac MyPackageClass.java
C:\Users\Your Name>javac -d . MyPackageClass.java
This forces the compiler to create the "mypack" package.
The -d keyword specifies the destination for where to save the
class file.
You can use any directory name, like c:/user (windows), or, if
you want to keep the package within the same directory, you
can use the dot sign ".", like in the example above.
When we compiled the package in the example above,
a new folder was created, called "mypack".
C:\Users\Your Name>java mypack.MyPackageClass
This is my package!
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();
}
}
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();
}
}
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();
}
}