Contenido del Curso
Java Extended
Java Extended
Importing Libraries
Using pre-existing libraries in our code.
You have already encountered the concept of libraries when we talked about JRE.
A library is an extension of a program's functionality. There are a vast number of libraries available, and in the future, you will even create your own libraries.
However, to avoid overloading the program and memory by constantly using all the libraries in our program (which could be hundreds), we use the import
keyword to add a specific library to our program.
In Java, the keyword import
is used to include classes or packages from other sources into the current code file. It allows a programmer to use functionality defined in other classes or packages without the need for fully qualified names of each element. By using imports, a programmer can simplify and improve the readability of their code.
The syntax will look like this:
Main
import parent.Child;
The parent library is located higher in the hierarchy than the child library. For example, let's say we have a class called Person
that we want to import, and it is located in the model package. To import it, we would use the syntax import model.Person;
since the Person
class is inside the model package.
We will learn more about classes and how to create them later in this course.
We also can import all child libraries using the following syntax:
Main
import parent.*;
Using .*
is not considered a best practice as it adds additional memory overhead and affects performance in general. Instead, it is better to use multiple imports. In code, it will look like this:
Main
import parent.Child1; import parent.Child2; import parent.Child3;
This way, we can see which specific libraries we import and what we need to use. Additionally, we avoid unnecessary memory overhead and improve the performance of our application.
In the next chapter, we will explore the practical usage of the import keyword and import a library into our code.
¡Gracias por tus comentarios!