Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Package vs Folder in Java. src\main\java doesn't need specifying package

Tags:

java

I was watching a lecture on Java when I caught myself not specifying package in Java file.

They lecturer was using Java 11 on Netbeans, and I Java 1.8 on IDEA. By default Netbeans created him a package, and the main java file has package specified.

But on IDEA, I noticed that I don't need to specify package name, when creating .java file inside src\main\java folder. And I have a question why?

  1. Why is src\main\java a folder, and not a package?
  2. What is the difference between a folder and a package?
  3. In Python, they create __init__.py file inside of a package, in order to make Python interpreter see the package. How is it working in Java, if there is no __init__ file? How does Java understand that this is a folder, and that is a package?
  4. Why does Java need to introduce and separate folder and package terms?

1 Answers

Why is src\main\java a folder, and not a package?

Which folders become packages depends on where the "root" is defined. In IDEA, src/java/main is the root. Any folders inside of that are mapped to packages. If for example, you create a folder src/java/main/foo and create a Foo.java in that folder, you will have a class named Foo in a package named foo.

What is the difference between a folder and a package?

A package is a way to group related Java classes. Sometimes a package is implemented as a folder in your file system. Sometimes it is something else. (See below.)

Why does Java need to introduce and separate folder and package terms?

One reason to differentiate between folders and packages is that some packages aren't folders. For example, you can download a .jar file from the Internet which contains a Java library. The library inside that .jar file defines packages and classes that you can use in your own code, but there are no folders for the packages.

The reason for a new term "package" is to create an abstraction that isn't tied to the folders in your local file system.

like image 130
Code-Apprentice Avatar answered Nov 24 '25 07:11

Code-Apprentice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!