Packages in Java
We have already encountered the concept of packages when we were learning about importing different libraries. Packages are the same, but now we will create them ourselves.
I have a class called "
Dog" and a
Main class. Earlier, we created these classes in the same file, but now we can do it nicely. I have split these classes into two different files. One file contains the "
Dog" class, and the other contains the
main class. Also, it's worth noting that the "
Dog" class is located in the "animals" package.
Here, it is worth reminding about a very useful IntelliJ feature. We can automatically generate various pieces of repetitive code. These could be:
toString()methods, and so on.
In our case, we want to generate the
toString() method. To do this, press the appropriate key combination:
- For Mac -
Command + N;
- For Windows -
Alt + Insert.
This will open a window with options. Choose the code generation option we want using the arrow keys and press Enter. Next, it will prompt us to choose how many fields we want to generate the
toString() method. Choose all fields and click OK.
toString() method will be automatically generated and ready to use!
How to import a package?
Let's go back to packages. We have already generated our
Dog class. Now, we need to create an object of this class and call its method in the
Main class. To do this, we need to import the
Dog class from the
animals package, but IntelliJ will do this for us. Next, our task is to create an object of the
Dog class using the constructor:
Great, we have successfully created an object of the
Dog class and printed information about it to the console using the overridden
How to create packages and classes inside
Now, let's understand how to create packages and classes within packages. To do this, we will create a package called
birds inside the
animals package and create a class called
Parrot within it:
- Right-click on the
srcfolder and select "Package" from the pop-up list. Enter the name of the package and click "Create."
- Now, with the
birdspackage created, we can create a class inside it. Right-click on the
birdspackage and select "Class." Give the class a name, in our case,
Parrot, and click "Create."
There's no need to be afraid of the extensive array of features you see when creating something. You won't have to use all of them right away (even I don't use them very often). With experience, you'll become familiar with most of these features, and I'll cover most of them in this course.
Everything was clear?