Daniel Scocco
Daniel Scocco

Reputation: 7266

Java files on the same folder and on the same package

At least on my machine when I put 2 Java class files on the same folder, without making them part of the same package, they already see one another, so from one file I can call a public class from the other file and vice-versa.

Questions:

  1. Is this the general case or a coincidence that may not work on every platform?

  2. If this is not a coincidence, I am guessing the purpose of packages is to allow you to organize your class files and make they share stuff, even if they are spread across different folders and paths. Is this correct or I am missing something?

Upvotes: 1

Views: 3197

Answers (3)

MikhailSP
MikhailSP

Reputation: 3313

  1. I sure it is general case, but it is bad approach.
  2. You are right, but more general reason to use package is to separate namespaces, for example, you have to create Car class, but there are many people who want to use this classname, thats why you have to use package, for example: com.yourcompany.yourproject. In such case you can use your Car class from your package without implicitly defining package and you also can use other Car classes in such manner: new com.google.general.Car(); In the java rules, it is recommend to use domain name right-to-left for providing unique package name.

Upvotes: 0

Kazekage Gaara
Kazekage Gaara

Reputation: 15052

If no package name is specified, the classes in the file go into a special unnamed package. And this is the same case for all files with no explicit package specification. Hence, they all fall into the special unnamed package, and exhibit the behavior that you are seeing.

You might want to go through this for a better understanding.

Upvotes: 2

chooban
chooban

Reputation: 9256

If they're in the same directory then they're in the same package, or are you copying .class files around after they've been written by the compiler?

Packages are a way of organising classes into a namespace. There are plenty of reasons to do this, the best bet is to start with the tutorial.

Upvotes: 0

Related Questions