top of page

Packages and Encapsulation

Avoiding Naming Collision- Packages in Java

Every java file was developed inside src. Let's take look at a scenario.

if 100 java files or somehow 1000 java files all were developed in src. what happens?

  • If the file count increases automatically managing difficulty also gets increased.

  • it is not advisable to develop more files in the same folder.

  • identifying a file can create conflict so going for less number of few files as possible.

How can we overcome this?
  • Instead of creating all java files in src, we can go for multiple folders let's say package1 contains some java files, package2 contains some java files, and com contains some java files.

  • Based on the usage or type we can go for folders.

How does the package work?
  • To group similar kinds of classes, we go for packages.

  • For every java file, we need to specify the package name as a folder name like package1.

  • The folder name is treated as packages and should be in lowercase.

Package package1;
class A //The current directory for this java file, is package1.
  • Not only java files we can have sub packages, and subdirectories.

  • The package name is the same as the directories.

Outer package.inner package;
//If we want to access the sub-packages mention the subpackage as a member of an outer package using . access operator.
  • In 1 folder we shouldn't create an file again and again.

  • if we are using packages not only encapsulate similar kinds of members in one package, we can also achieve avoiding naming collisions.

what we inferred?

  • what a package is and why we should use them

  • package declaration must be the first statement, followed by package import

  • Java uses file system directories to store packages.

  • Java packages provide access control to the classes

  • Packages in Java add another dimension to access control or access specifiers which in turn represent data encapsulation or data hiding.

  • easily figure out the classes, interfaces, enumerations, and annotations that are related.

  • It improves efficiency and coding style but also reduces a lot of additional work.

18 views0 comments
bottom of page