Importing a package allows me to import a class, or set of classes into my application that I can use. (These will be outside of the package that I create for my own project.)
These packages act like libraries in other languages where a lot of work might be done for you already, and you are getting to take advantage of that developer(s) work. That developer might even be you, as you build your own libraries of classes to help you accomplish your normal tasks.
The package you import might come with Java, and just not automatically be imported, or it might be from a third party, or even yourself since you can create your packages.
Packages are set up to organize different features, so you don’t import everything into your project. It also allows the same name for a class to be used, but to be in different packages, just as Date
, which is in java.sql
and java.util
. Each class is different in that it functions based upon what it would be expected based upon the package it belongs to, whether as a date from a SQL database that is mainly stored and accessed, or a date during normal computation.
In Java, you don’t have to import libraries, as you could reference it by the full name, java.util.Date
for example, when you specify the data type of an object you are going to create, and sometimes you still have to if there is any potential confusion between two libraries you’ve imported, but normally you won’t since you’ll use the import to make your life easier by not writing as much code..
When you import a package, you will do it outside of your class definition. Imports should be the first thing in your file actually. And you will use the keyword import, followed by the fully qualified package name you want to import.
If you are importing the whole package, you place a .*
at the end of the package name, to import all of the classes. If you are importing just a single class, you can put a .<class name>
at the end of the package name. Your code will be finished with a semi-colon.
import java.util.*; // importing the whole java.util package
import java.sql.Date; // importing just one class from a package
Importing a Package was originally found on Access 2 Learn