Why have the package declaration at all?

so I have a class with “package world.somefolder” at the top. What’s the point in defining packages? Can’t you just put the java files in their respective folders and just compile them? Why the need to specify which folders they’re in? Maybe I’m just missing some functionality that package provides?

I’m no Java expert, but I always though that was to keep things grouped. Not only for convention’s sake, but also to help prevent naming clashes.

A couple of reasons for packages are: to avoid duplicating code and to encourage programmers to think about the ‘reuseability’ of their code.

Let’s look at a heavily contrived example of coding without packages.

You want to make a Cake, so you write Flour, Eggs and Milk and combine them in your Cake class. Works great.

Now you want to make Bread, so you copy Flour, Eggs and Milk to your Bread folder and modify them such that when you combine them in your Bread class, they now make Bread. Still kind of okay, but now you have two, incompatible, versions of Flour, Eggs and Milk.

Sometime later, you decide to make Pancake, should you copy the Cake:Flour or the Bread:Flour? Well, I guess it really doesn’t matter, you’re just going to rewrite Flour, again, to suit your needs for Pancake.

Now, again, with packages.

You decide to make a Cake, so you write Flour, Eggs and Milk, focusing not only on making them work, but also looking forward towards reuseability, and put them into the ingredient package. You import those classes into Cake and away you go.

Moving onto Bread, you import Flour, Eggs and Milk and finish your project in record time.

Later, when you decide that those Pancakes would be tasty, you, again, import Flour, Eggs and Milk, and have your Pancakes in little time.