0% found this document useful (0 votes)
7 views

Java_Packages

The document provides an overview of Java packages, including their definition, benefits, and how to create and manage them. It explains the importance of packages for organizing classes, avoiding name conflicts, and controlling access to class members. Additionally, it covers built-in and user-defined packages, the CLASSPATH, and the use of import statements to simplify class access.

Uploaded by

Rishav Dev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java_Packages

The document provides an overview of Java packages, including their definition, benefits, and how to create and manage them. It explains the importance of packages for organizing classes, avoiding name conflicts, and controlling access to class members. Additionally, it covers built-in and user-defined packages, the CLASSPATH, and the use of import statements to simplify class access.

Uploaded by

Rishav Dev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

1

PACKAGES

PACKAGES: DEFINING A PACKAGE, FINDING


PACKAGES AND CLASSPATH, ACCESS PROTECTION,
IMPORTING PACKAGES.
Packages: 2

 Defining a Package
 Finding Packages and CLASSPATH
 Access Protection
 Importing Packages
Packages:
3

Basics:
• Packages are containers for classes that are used to keep the class name space
compartmentalized. (Is used to group related classes. Think of it as a folder
in a file directory)

• Eg: A package allows you to create a class named List, which you can store in
your own package without concern that it will collide with some other class
named List stored elsewhere. (packages are used to avoid name conflicts)

• Packages are stored in a hierarchical manner and are explicitly imported into
new class definitions.
• A Java’s mechanism for partitioning the class name space into more
manageable chunks.
Packages:
4
Basics: ...
• The package is both a naming and a visibility control
mechanism.

• One can define classes inside a package that are not accessible
by code outside that package.

• Also define class members that are only exposed to other


members of the same package.

• This allows your classes to have intimate knowledge of each


other, by not exposing that knowledge to the rest of the world.
Packages:
5
 The benefits of organising classes into packages are:
• The classes contained in the packages of other programs/applications can be
reused.
• In packages classes can be unique compared with classes in other packages.
Like two classes in two different packages can have the same name. If there
is a naming clash, then classes can be accessed with their fully qualified
name.
• Classes in packages can be hidden if we don’t want other packages to access
them.
• Also provide a way for separating “design” from coding.
• Packages enable grouping of functionally related classes.
Packages:
6
Packages are divided into two categories:
• Built-in Packages (packages from the Java API)
• User-defined Packages (create your own packages)
 Built-in Packages
o The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.
o The library contains components for managing input, database programming, and
much much more.
o The library is divided into packages and classes. Meaning you can either import a
single class (along with its methods and attributes), or a whole package that contain all
the classes that belong to the specified package.
o To use a class or a package from the library, you need to use the import keyword.
Packages:
7
 User-defined Packages
o To create your own package, you need to understand that Java
uses a file system directory to store them. Just like folders on
your computer:

 To create a package, use the package keyword


Packages:
8
Basics: ...
 The Java Foundation Packages
• Java provides a large number of classes grouped into different packages
based on their functionality.
 The six foundation Java packages are:
• java.lang: Classes for primitive types, strings, math functions, threads, and exception

• java.util: Classes such as vectors, hash tables, date etc.


• java.io: Stream classes for I/O

• java.awt: Classes for implementing GUI – windows, buttons, menus etc.

• java.net: Classes for networking


• java.applet: Classes for creating and implementing applets
Packages:
The Java Foundation Packages 9
Packages:
Defining a Package: 10

➢Include a package command as the first statement in a Java source file.


Any classes declared within that file will belong to the specified package.

➢The package statement defines a name space in which classes are


stored. If you omit the package statement, the class names are put
into the default package, which has no name.
➢While the default package is fine for short, sample programs, it is
inadequate for real applications. Most of the time, you will define a
package for your code.
➢General Form: package pkg; Eg: package MyPackage;
Packages:
11
Defining a Package: ...
• Java uses file system directories to store packages. For example, the .class
files for any classes you declare to be part of MyPackage must be stored
in a directory called MyPackage.
• Remember that case is significant, and the directory name must match
the package name exactly.
• More than one file can include the same package statement. The package
statement simply specifies to which package the classes defined in a file
belong. It does not exclude other classes in other files from being part of
that same package.
• Most real-world packages are spread across many files.
Packages:
12
Defining a Package: ...
• You can create a hierarchy of packages. To do so, simply separate each
package name from the one above it by use of a period. The general
form of a multileveled package statement package
pkg1[.pkg2[.pkg3]];
• A package hierarchy must be reflected in the file system of your Java
development system.
• Eg: A package declared as package java.awt.image; needs to be stored
in java\awt\image in a Windows environment.
• Be sure to choose your package names carefully. You cannot rename a
package without renaming the directory in which the classes are stored.
Packages:
13
Finding Packages and CLASSPATH:
• Packages are mirrored by directories. This raises an important question: How does
the Java run-time system know where to look for packages that you create?

• The answer has three parts.


✓First, by default, the Java run-time system uses the current working directory
as its starting point. Thus, if your package is in a subdirectory of the current
directory, it will be found.

✓Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable.

✓Third, you can use the -classpath option with java and javac to specify the
path to your classes.
Packages:
14
Finding Packages and CLASSPATH: ...
• Eg: package MyPack; In order for a program to find MyPack, one of three things
must be true.
✓ Either the program can be executed from a directory immediately above MyPack, or
✓ the CLASSPATH must be set to include the path to MyPack, or
✓ the -classpath option must specify the path to MyPack when the program is run via
java.
• When the second two options are used, the class path must not include MyPack, itself. It must simply
specify the path to MyPack. For example, in a Windows environment, if the path to MyPack is
C:\MyPrograms\Java\MyPack Then the class path to MyPack is
C:\MyPrograms\Java\MyPack
Packages:
•A Short Package Example 15

Call this file AccountBalance.java and


put it in a directory called MyPack.
Next, compile the file. Make sure that
the resulting .class file is also in the
MyPack directory. Then, try executing
the AccountBalance class, using the
following command line:
java MyPack.AccountBalance
Remember, you will need to be in the
directory above MyPack when you
execute this command.
AccountBalance is now part of the
package MyPack. This means that it
cannot be executed by itself.
Packages:
Finding Packages and CLASSPATH: 16
• A Short Package Example ...
Packages:
17

Access Protection:
• Packages add another dimension to access control. Java provides many
levels of protection to allow fine-grained control over the visibility of
variables and methods within classes, subclasses, and packages.

• Classes and packages are both means of encapsulating and containing


the name space and scope of variables and methods.

• Packages act as containers for classes and other subordinate packages.


• Classes act as containers for data and code. The class is Java’s smallest
unit of abstraction.
Packages:
18

Access Protection: ...


• Because of the interplay between classes and packages, Java addresses
four categories of visibility for class members:
➢Subclasses in the same package
➢Non-subclasses in the same package
➢Subclasses in different packages
➢Classes that are neither in the same package nor subclasses

• The three access specifiers, private, public, and protected, provide a


variety of ways to produce the many levels of access required by these
categories.
Packages:
19
Access Protection: ...
• While Java’s access control mechanism may seem complicated, we can
simplify it as follows:
o Anything declared public can be accessed from anywhere.
o Anything declared private cannot be seen outside of its class.
o When a member does not have an explicit access specification, it is visible to
subclasses as well as to other classes in the same package. This is the default
access.
o If you do not want to allow an element to be seen outside your current
package, but only to classes that subclass your class directly, then declare that
element protected.
Packages:
20
Access Protection: ...
•Class Member Access - Applies only to members of classes.
A non-nested class has only two possible
access levels: default and public. When a
class is declared as public, it is accessible
by any other code.

If a class has default access, then it can


only be accessed by other code within its
same package.

When a class is public, it must be the only


public class declared in the file, and the
file must have the same name as the class.
Packages:
21
Access Protection:..
• An Access Example
Packages:
Access Protection: ... 22
• An Access Example ...
Packages:
23

An Access Example ...


Packages:
24
Importing Packages:
• Given that packages exist and are a good mechanism for compartmentalizing
diverse classes from each other, it is easy to see why all of the built-in Java
classes are stored in packages.
• There are no core Java classes in the unnamed default package; all of the
standard classes are stored in some named package. Since classes within
packages must be fully qualified with their package name or names, it could
become tedious to type in the long dot-separated package path name for
every class you want to use.

• For this reason, Java includes the import statement to bring certain classes,
or entire packages, into visibility. Once imported, a class can be referred to
directly, using only its name
Packages:
25
Importing Packages: ...
• The import statement is a convenience to the programmer and is not
technically needed to write a complete Java program. If you are going to
refer to a few dozen classes in your application, however, the import
statement will save a lot of typing.
• In a Java source file, import statements occur immediately following the
package statement (if it exists) and before any class definitions. The
general form of the import statement:

import pkg1[.pkg2].(classname|*);
• Here, pkg1 is the name of a top-level package, and pkg2 is the name of a
subordinate package inside the outer package separated by a dot (.).
Packages:
26
• There is no practical limit on the depth of a package hierarchy, except that
imposed by the file system. Finally, you specify either an explicit classname
or a star (*), which indicates that the Java compiler should import the entire
package.
• This code fragment shows both forms in use:
import java.util.Date;
import java.io.*;
• CAUTION The star form may increase compilation time specially if you
import several large packages. For this reason it is a good idea to explicitly
name the classes that you want to use rather than importing whole packages.
However, the star form has absolutely no effect on the run-time performance
or size of your classes.
Packages:
27
Importing Packages: ...
• All of the standard Java classes included with Java are stored in a package
called java.
• The basic language functions are stored in a package inside of the java
package called java.lang
• Normally, you have to import every package or class that you want to use,
but since Java is useless without much of the functionality in java.lang, it
is implicitly imported by the compiler for all programs. This is equivalent
to the following line being at the top of all of your programs:
import java.lang.*;
• If a class with the same name exists in two different packages that you
import using the star form, the compiler will remain silent, unless you try
to use one of the classes. In that case, you will get a compile-time error
and have to explicitly name the class specifying its package.
Packages:
28
Importing Packages: ...
• It must be emphasized that the import statement is optional. Any place you
use a class name, you can use its fully qualified name, which includes its full
package hierarchy.

• For example, this fragment uses an import statement:


import java.util.*;
class MyDate extends Date {
}
• The same example without the import statement looks like this:
class MyDate extends java.util.Date { }
Packages:
29

Importing Packages: ...


• When a package is imported, only those items within the
package declared as public will be available to non subclasses
in the importing code.

• For example, if you want the Balance class of the package


MyPack shown earlier to be available as a stand-alone class for
general use outside of MyPack, then you will need to declare it
as public and put it into its own file.
Packages:
30
Packages:
Handling name conflicts 31

❑ The only time we need to pay attention to packages is when we have a name conflict.
❑ For example both, java.util and java.sql packages have a class named Date. So if we
import both packages in program as follows:

❑ The compiler will not be able to figure out which Date class do we want. This problem
can be solved by using a specific import statement:
Packages:
Illustration of user-defined packages: 32
Creating our first package: File name – ClassOne.java Creating our second package: File name – ClassTwo.java

Making use of both the created packages: File name –


Testing.java

You might also like