We already know that Java has packages from its API and we usually import classes from the java.util
package.
In this tutorial we will show you how to create your own packages in: GNU/LINUX, *BSD, macOS and in WSL/Windows and import them into your own .
Suppose you create a class with a single method and you want to make it available to anyone who wants to import:
vim MyClass.java
On the first line use the keyword package
followed by a space and the name you want for your package, example: MyPackage;
and then create your class with the methods you want to share, example public void myMethod( )
, which just returns any string:
package MyPackage;
public class MyClass {
public void myMethod() {
System.out.println("This is my package!");
}
}
Now let’s create the package directory already with this class with the command:
javac -d . MyClass.java
Note that inside your project (in this case: sandbox) there is now a directory named MyPackage/
with the following files inside and outside it:
tree
sandbox/
sandbox/
├── MyPackage
│ └── MyClass.class
└── MyClass.java
1 directory, 2 files
If you want, we can even remove the file sandbox/MinhaClasse.java
and now the project(sandbox) will only have one directory and inside it a file MinhaClasse.java
that was not what we removed, but the file inside the MyPackage directory:
sandbox/
└── MyPackage
└── MyClass.class
1 directory, 1 file
Now let’s import our package into another file, another project that you are creating:
vim MyProgram.java
import MyPackage.MyClass;
public class MyProgram {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.myMethod();
}
}
That is, when instantiating the package class and calling the method, it is successfully executed:
javac MyProgram.java
java MyProgram
Possible and probable output:
This is my package!
.
Let’s say you have a new class and you want to add it to your package: MyPackage
package MyPackage;
public class NewClass {
public String newMethod(){
String name = "For example only";
return name;
}
}
Now run:
javac -d . NewClass.java
If you want after running the command, remove the file:
rm ./NewClass.java
Now in your MyProgram.java
code also import this NewClass
class:
import MyPackage.MyClass;
import MyPackage.NewClass;
public class MyProgram {
public static void main(String[] args) {
MyClass obj = new MyClass();
NewClass obj2 = new NewClass();
obj.myMethod();
System.out.println(obj2.newMethod());
}
}
After compiling and running the possible output will be:
That's my package!
just for example
If you wanted to import all the classes in your package, just use: import MyPackage.*;
:
MyProgram.java
import MyPackage.*;
public class MyProgram {
public static void main(String[] args) {
MyClass obj = new MyClass();
NewClass obj2 = new NewClass();
obj.myMethod();
System.out.println(obj2.newMethod());
}
}