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:
Now let’s create the package directory already with this class with the command:
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/
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:
Now let’s import our package into another file, another project that you are creating:
vim MyProgram.java
That is, when instantiating the package class and calling the method, it is successfully executed:
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
Now run:
If you want after running the command, remove the file:
rm ./NewClass.java
Now in your MyProgram.java
code also import this NewClass
class:
After compiling and running the possible output will be:
If you wanted to import all the classes in your package, just use: import MyPackage.*;
:
MyProgram.java