Table of Contents
Java packages are used to organize our code and to avoid naming conflicts. Packages strongly resemble folders like the ones found in file directory. Every package has a unique name so that class names can still be duplicated and still be used properly if you import it from the right package. There are two kinds of packages, the built-in ones and the ones you can create yourself.
You have one of these on the way too.
Creating a Package
Create a package using the package
keyword, and then the name of the package. Ensure that this is the top of the file.
JAVApackage devices;
public class Phone {
private String name;
public Phone(String name) {
this.name = name;
}
public int getName() {
return name;
}
}
This class now lives inside the devices
package.
Importing a Class
You can import a class of your choosing by using the import
keyword and specifying the exact package and class name:
JAVAimport java.lang.Math;
That, for example, imports the Math
class only. This makes everything from Math
available in whatever class you imported it into.
Importing a Package
If you find yourself using multiple classes from the same package, you can just import an entire package to get all the classes inside available:
JAVAimport java.lang.*;
This imports all the classes inside the java.lang
package.
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue
- How To Create a Modal Popup Box with CSS and JavaScript