PACKAGES

Putting classes together

Benefits of using packages in java

   The classes contained in packages of other programs can be easily reused

   Here, classes can be unique compared with classes in other packages

   It provide a way to hide classes

   It provides a way to separate design from coding

Java packages

   Java API Packages

   User defined packages

Java API Packages

Java API provides a large amount of classes grouped into different packages according to the functionality

Frequently used API Packages


Java System packages and classes









Using System Packages

  The packages are organized in a hierarchical structure.

  Package named java contains the package awt, which in turn contains various classes required for implementing GUI

Hierarchical representation of java. awt package



Accessing classes stored in package

·                  Use fully classified classname of the class that we want to use

              import packagename.classname

                                    import Java.awt.Color

·                  Accessing the whole classes of a particular package

                                    import package name.*;

              import java.awt.*;

Naming conventions

    Packages begins with lowercase letters

    Class names begin with uppercase

    Methods begin with lowercase


Creating packages

     Declare the name of the package using the keyword package followed by package name

     This must be the first statement in the code





     Here package name is firstPackage

     Should be saved in the name ‘firstClass.java’

     Located in the directory named ‘firstPackage

     This directory should be the subdirectory of the directory where classes imports this package located

  

Summary of the process to be done to create a package

     Declare the package at the beginning

     Define the class that is to be put in the package and declare public

     Create a sub directory under the directory where the main source code stored.

     Store the listing file as classname.java in sub directory created

     Compile the file

Accessing the package

    Using import statement

General form:

                                import package1[.package2][package3].classname;

Using package

     Package named package1 contains a single class ClassA 

     Souce file should  be saved as ClassA.java

     Stored in the subdirectory package1

     Compile this java file

 

Program in the parent directory






    Imports the class ClassA from package1

    Source file should be saved as PackageTest1.java


Access Protection



No comments:

Post a Comment