Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Java packages? [duplicate]

Tags:

java

Why do we use packages in Java? How to use them?

like image 409
rajesh Avatar asked Aug 23 '26 04:08

rajesh


1 Answers

Packages are mostly just a way of organizing code. The JDK has thousands of classes in, and a large application has thousands more. Why would you not want to organize those into some sort of hierarchy allowing you to find the classes you're interested in easily?

Packages also participate in access control in Java (but not in .NET, interestingly) - but I'd say the main purpose is to help humans organize their code meaningfully.

It also means that occasionally you may want or need the same class name in multiple packages - where the package name effectively provides the context. Now if you're working in a single codebase for a single application, that's usually something to try to avoid - but if you've got a large codebase where many different applications use many different parts of it, that may be better than trying to have a unique name for every single class. (A typical example of this is in user interface code - just looking in the .NET libraries, there's a "Button" class in three separate namespaces, for three separate UI frameworks.)

like image 78
Jon Skeet Avatar answered Aug 25 '26 19:08

Jon Skeet