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 [Link]; // Import a single class import
[Link].*; // Import the whole package
Import a Class
import [Link];
Import a Package
import [Link].*;
import [Link];
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner([Link]);
[Link]("Enter username");
String userName = [Link]();
[Link]("Username is: " + userName);
}
}
User-defined Packages
package mypack;
class MyPackageClass {
public static void main(String[] args) {
[Link]("This is my package!");
}
}
To create a package, use the package keyword.
C:\Users\Your Name>javac [Link]
C:\Users\Your Name>javac -d . [Link]
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 [Link]
This is my package!
Using packagename.*
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Using [Link]
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Using fully qualified name
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}