World's most popular travel blog for travel bloggers.

Explain the need of package in Java. Explain accessibility rules for packages.

, , No Comments

 Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.

Advantages of using a Package in Java

  • Reusability - While developing a project in java, we often feel that there are few things that we are writing again and again in our code. Using packages, you can create such things in form of classes inside a package and whenever you need to perform that same task, just import that package and use the class.

  • Better Organization - Again, in large java projects where we have several hundreds of classes, it is always required to group the similar types of classes in a meaningful package name so that you can organize your project better and when you need something you can quickly locate it and use it, which improves the efficiency.

  • Name Conflicts - We can define two classes with the same name in different packages so to avoid name collision, we can use packages.

There are 4 types of java access modifiers :

  • private - The private access modifier is accessible only within class.

  • default - If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.

  • protected - The protected access modifier is accessible within package and outside the package but through inheritance only.

  • public - The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.


Post a Comment

Let us know your responses and feedback