Welcome to the exciting world of Java 9 and its powerful new feature - Modules! π
In this tutorial, we'll explore why Modules are a game-changer for Java developers, and learn how to use them in your projects. Let's dive in!
In Java 9, Modules are a way to organize and manage your code into reusable and modular units. Modules help you to:
π‘ Pro Tip: Think of Modules as the building blocks of your Java applications!
Every Java project consists of at least one module, called the root module. To create a module, you simply need to name the source folder as module-name and create a module-info.java file within it.
Let's create a simple module named myFirstModule.
Create a new directory called myFirstModule and place your Java files inside.
myFirstModule
β
β MyFirstClass.java
β
ββββsrc
ββββmain
ββββjava
ββββcom.myapp
ββββmyFirstModule
ββββMyFirstClass.java
In the myFirstModule directory, create a new file called module-info.java. This file should contain a module declaration with the module name and its version.
module com.myapp.myFirstModule {
}To make your module available for other projects, you need to export it using the exports directive in the module-info.java file.
module com.myapp.myFirstModule {
exports com.myapp.myFirstModule;
}Now, to use another module in your project, you can specify its dependency in the module-info.java file using the requires directive.
module com.myapp.myFirstModule {
requires com.myapp.otherModule; // assuming otherModule is the name of the other module
exports com.myapp.myFirstModule;
}Open modules allow access to the public types of all the modules they depend on. This is useful when you want to access APIs of other modules.
open module com.myapp.myFirstModule {
exports com.myapp.myFirstModule;
}If you don't provide a module-info.java file, Java will automatically create a module for your project. This is called an automatic module.
What is the purpose of a module in Java 9?
By now, you should have a good understanding of Modules in Java 9! Practice organizing your code into Modules and try out the concepts you've learned in your projects. Happy coding! π
In the next tutorial, we'll dive deeper into advanced Java 9 features. Stay tuned! π―