Packages

Package in java is nothing but a kind of directory which contains a group of similar types of classes, interfaces and subpackages. Packages can be created by right click on the src folder and select option package and give it a name.

Package

You need to use the keyword package in the program to access the components in that package.Packages can be categorized in 2 categories.

  • In-built packages
  • user defined packages

In-built packages are like java, lang, awt, javax, swing, util, sql, io ,net etc.

User defined packages can be like any desired name which suits the requirement.In our example ,we have create a packages called com.testingpol.demo.(as shown below)

Advantages of packages:

  • Packages can be used to maintain the similar kind of classes in one directory.
  • Remove naming collision.
  • Provides access protection.

Subpackages : It will be created inside a package to further clarify it. In our example, we have full package name com.testingpool.demo. In that, testingpool and demo are the subpackages of com.

The standard for defining a package is domain.company.package. e.g. com.testingpool.demo

The import keyword is used to access the package from outside. For showing this example, we have created 2 packages com.testingpool.demo and com.testingpool.demo2. A class AddNum is created under the package com.testingpool.demo  and another class SubNumber is created under another pacage com.testingpool.demo2.

Now, if we want to create object of class AddNumber in the second package com.testingpool.demo2.We have to import the first package inside the second package.Look at the below example for better understanding.

Class AddNumber under the package com.testingpool.demo.

Class SubNumber under the package com.testingpool.demo2.

There are 3 ways to access the package into another class or package.

  • By packagename.*
  • By package.classname
  • By using fully package name

Using package.*:

Using Package.classname:

AddNumber is the class under the package com.testinpool.demo.

using full package name:

Instead of importing the package, use the full package name to use its components as shown below.

 

 

 

 

Methods and return value
Static keyword
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *