Java Object Oriented Programming - Package


A package is a mechanism provided by Java for partitioning class name space into more manageable chunks. Basically it's a group of classes.

Packages provide convenience for organizing work and for separating your work from code libraries by others.

Packaging provides us these two main functions:

  1. Naming control mechanism.
  2. Visibility control mechanism.

Naming Control

Without a package, you have to provide a unique name for all your classes so as to avoid name collisions.

If you have many classes, this may be a problem. It's even a bigger problem if you are working in teams. You'll have to constantly ask each other the names you are using for naming classes. Clearly we need a better way.

Packages guarantee the uniqueness f class names.

Visibility Control

Packages influence the visibility in that we can define a class inside a package that is not visible to code outside the given package.

Furthermore you can create class members that are visible only to other members of the same package,

This provides data hiding and encapsulation which are core pillars of Object Oriented Programming. This results in more maintenable code.

Defining a Package

Packages are created by including the package keyword as the first statement in the Java source file.

package myPackageName;

myPackageName is the name of our package here.

Then classes you declare within that file will belong to the specified package.

Ommiting the package declaration makes you classes be put in the default package.

How Java Packages are Represented

Java will use the file system directories/folders to store the packages.

For instance if we have several classes files inside myPackageName package, then they will be stored in the same folder. A folder called myPackageName. The directory name will exactly match the package name.

Package Hierarchies

Hierarchy of packages are allowed. For example the standard java packages are hierarchical.

The same way you have nested subdirectories you can organize packages with various levels of nesting.

You just separate each package name from the one above it by use of a period.

package myPkg1[.myPkg2[.myPkg3]];

Example

package java.awt.image;

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post