No matter if you are a Windows or Mac user, you always use folders to keep your files inside it. So that all the related files are grouped together.
Same applies for java as well. To group all the related classes and Interfaces together, we use Package.
A java Package is quite similar to a folder. And as we know Classes and Interfaces are stored in a '.java' file. Similarly, the java files are stored in a Package, the same way Windows and Mac users stores their files inside a folder.
So, a java package is something where all the related classes and Interfaces are kept.
A java package can be created using the package keyword and it should be the first statement in the file.
Let's say we want to keep a java file 'Human.java'(Which contains a 'Human' class) inside a package named 'myownpackage'.
So, let us understand this with the below example :
In the above case we have a file called 'Human.java' . Inside the file we have declared the package 'myownpackage' using the package keyword.
And a folder named 'myownpackage' will be created and the java file 'Human.java' will be saved inside it.
Also let us say we have an 'Animal' class inside a java file 'Animal.java' . And we wanted to keep it inside the same package i.e. myownpackage.
Similarly, we have created a file 'Animal.java' and declared the package 'myownpackage' using the package keyword.
Now, along with the file 'Human.java', 'Animal.java' will also be stored in it.
Let us say, we have created a different package named 'mainpackage' that has the 'main()' method. And we need to use both the 'Human' and 'Animal' object in it.
The above example is quite simple. We are using the objects of Human and Animal and setting some values and displaying them.
The only catch is Human and Animal class belongs to a different package. Just have a look at the below diagram :
The Main.java is in a package called 'mainpackage' and both 'Animal.java' and 'Human.java' are in 'myownpackage'.
Now, to use 'Animal' and 'Human' objects in the 'Main' class, we have used the 'import' statement.
The above statement imports all the classes available in 'myownpackage'.
Also, you can import individual classes using 'import' statement:
The above statement will allow you to use only Animal class.
Similarly, the statement:
Will allow you to import only the Human class.