Java packages tutorial part 1

Java packages explained, how to structure Java package and info about default package.

Imagine you have an application with lots of classes. It's quite common. Even very small projects have dozens of classes. In medium sized projects are hundrets of classes and in big projects are thousands of classes at minimum.

And don't forget about libraries that every project use. They have classes as well.

What are classes? They are files with the same name and with suffix java. They are all in project sources directory.

How to divide classes so that they all wouldn't be in one place? Using packages. What are packages? When classes are files, than packages must be ... that's right – directories. Like directories have sub-directories, packages have sub-packages.

There's also a convention, that packages are in form of reversed URL pattern. They typically start with com or org, next is project name, subproject name and so on.

Now you see, that this structure is much better, than having all classes in one package.

By the way, can you have Java class, that isn't in any package? Yes, you can. When class isn't in any package, it's also called, that such class is in default package. And you should never ever do that. Every class should be in some package.

And this information is also in every class. See package declaration, which is in every Java class, that is in some package.

comments powered by Disqus


Free online Java web application examples

Want to develop whole web applications which use database, security and more? See my github account, where are lot's of example projects: