0

how to create and access package in java

Package

Package is defined as the collection of classes, interfaces and sub-packages.it is a name space in which classes are stored
package keyword is used to define the package
package have 2 types

  • Built-in package(eg.- java, lang, awt, javax, swing, net, io, util, sql)
  • User defined package

Advantage of java Package

  • package is used to categorize the classes and interfaces so that they can be easily maintain
  • package provide access protection.
  • Java package removes naming collision.

For example

In above example we have to create a package P1. Here package is keyword to define the package.the access of the class is public.
Than msg() method is create to print the our message “Package p1”
After that we compile our code with filename.The following syntax is used to compile the code

The -d switch specifies the destination where to put the generated class file. and .(dot) is used to current directory
after compile the code our class file in generated in package P1

access package from another package

to access the package we have to use import keyword and package name
There are 3 ways to access the package.

  • import package.*;
  • import package.classname;
  • fully qualified name.

Package Access using packagename.*

example:-

In above example package MyPack is created. For access the package we have used import keyword and P1.* to access all class in package P1. Than the main method is created of Pack2 and object of class Pack1 is created in main method than method msg() of package P1 is we have access in class Pack2.
Than compile the code as

Output
package

Pravesh Kumar

Leave a Reply

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