Packages in Java
Packages can be defined as a pack of similar classes and interfaces which are grouped together.
It is used to avoid naming conflicts in which same names can be used for classes differentiating the classes in package names.
We can define our own package name and can bundle classes and interfaces however we needed.
To define a package
package package-name;
Example
package electrical;
class Bulb{
void turnon(){
System.out.println("Bulb is turned on");
}
void turnoff(){
System.out.println("Bulb is turned off");
}
public static void main(String args[]){
Bulb b=new Bulb();
b.turnon();
b.turnoff();
}
}
To compile the java file with package name in command prompt or shell
javac -d destination_folder Filename.java
To point to current destination folder you can use .(dot) symbol.
Example
javac -d . Filename.java
To run
java Filename
To use a class or interface from another package i.e for object creation or for extending, we should import the necessary class files from other packages which is generated while compiling.
To import a class file from another package
Way 1
import package_name.*;
Example
package 1
package electrical;
public class Bulb{
public void turnon(){
System.out.println("Bulb is turned on");
}
public void turnoff(){
System.out.println("Bulb is turned off");
}
}
package 2
package mine;
import electrical.*;
public class MainActivity{
public static void main(String args[]){
Bulb b=new Bulb();
b.turnon();
b.turnoff();
}
}
Way 2
import package_name.class_name;
This imports only the particular class in the package.
Example
package 1
package electrical;
public class Bulb{
public void turnon(){
System.out.println("Bulb is turned on");
}
public void turnoff(){
System.out.println("Bulb is turned off");
}
}
package 2
package mine;
import electrical.Bulb;
public class MainActivity{
public static void main(String args[]){
Bulb b=new Bulb();
b.turnon();
b.turnoff();
}
}
Way 3
packagename.class_name
We can use wherever we use the class with its package name.
Example
package 1
package electrical;
public class Bulb{
public void turnon(){
System.out.println("Bulb is turned on");
}
public void turnoff(){
System.out.println("Bulb is turned off");
}
}
package 2
package mine;
public class MainActivity{
public static void main(String args[]){
electrical.Bulb b=new electrical.Bulb();
b.turnon();
b.turnoff();
}
}