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

Packages in Java

Packages in Java are used to group related classes and interfaces, providing benefits such as reusability, organization, and avoidance of naming conflicts. Java has built-in packages like java.lang, java.util, and java.io, and allows for user-defined packages. Classes can be accessed using fully qualified names or by importing packages, and the structure of packages must be reflected in the file system.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Packages in Java

Packages in Java are used to group related classes and interfaces, providing benefits such as reusability, organization, and avoidance of naming conflicts. Java has built-in packages like java.lang, java.util, and java.io, and allows for user-defined packages. Classes can be accessed using fully qualified names or by importing packages, and the structure of packages must be reflected in the file system.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

• Packages are Java’s way of grouping a number of related classes and/or

interfaces together into a single unit. That means, packages act as “containers”
for classes.
• 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. ie
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.
- Packages also provide a way for separating “design” from coding.
JAVA API PACKAGES

Java provides a large number of classes groped into different packages based on
their functionality
• The six foundation Java packages are:
- java.lang :
Contains classes for primitive types, strings, math functions, threads, and exception.
- java.util :
Contains 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 app.
Using System Packages

• The packages are organised in a hierarchical structure .For example, a


package named “java” contains the package “awt”, which in turn contains
various classes required for implementing GUI (graphical user interface).
Java “java” Package containing
JAVA
“lang”, “awt”,.. packages;
Can also contain classes.

awt
awt package containing classes.
graphics
font
Classes containing methods
image
Accessing Classes from
Packages
There are two ways of accessing the classes stored in packages:
• Using fully qualified class name
java.lang.Math.sqrt(x);
• Import package and use class name directly
import java.lang.Math
Math.sqrt(x);
• Selected or all classes in packages can be imported:

import package.class;
import package.*;

• Implicit in all programs: import java.lang.*;


• package statement(s) must appear first
Packages in Java
• A package in Java is used to group related classes.
Think of it as a folder in a file directory.

• We use packages to avoid name conflicts, and to write a better


maintainable code.

• Packages are divided into two categories:


•Built-in Packages (packages from the Java API)
•User-defined Packages (create your own packages)
Built-in Packages
• The Java API is a library of prewritten classes, that are
free to use, included in the Java Development
Environment.
• The library contains components for managing input,
database programming, and much more.
• The library is divided into packages and classes.
• We 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.
• To use a class or a package from the library, we need to use the import
keyword:
• Syntax
• import package.name.Class; // Import a single class
• import package.name.*; // Import the whole package

• Example: import java.util.Scanner


• Here:
→ java is a top level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.
Advantages of using a package in Java
• Reusability: While developing a project in java, we often feel
that there are few things that we are writing again and again in
our code. Using packages, you can create such things in form
of classes inside a package and whenever you need to perform
that same task, just import that package and use the class.
• Better Organization: Again, in large java projects where we
have several hundreds of classes, it is always required to group
the similar types of classes in a meaningful package name so
that you can organize your project better and when you need
something you can quickly locate it and use it, which improves
the efficiency.
• Name Conflicts: We can define two classes with the same
name in different packages so to avoid name collision, we can
use packages
How to Create a package?

• Choose the name of the package


• Include the package command as the first line of code in your Java
Source File.
• The Source file contains the classes, interfaces, etc you want to
include in the package
• Compile to create the Java packages
1.To put a class into a package, at the first line of
code define package p1
2.Create a class c1
3.Defining a method m1 which prints a line.
4.Defining the main method
5.Creating an object of class c1
6.Calling method m1
Defining a package
• Simply 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 package statement the class names are put into the default
packages which has no name.

• Default packages is inadequate for real applications.


General form
• Package pkg;
• Example : package MyPackage;
• Java uses file system directories to store packages.
• The .class file for any classes you declare to be part of MyPackage
must be stored in a dirtectory called myPackage.
• Directory name must match the package name extactly.
• More than one file can include the same package statement.
• The package statement specifies to which package the classes
defined in a file belong.
• We can create a hierarchy of pacakages.
• Separate each package name from the one above it by use of a
period.
• The general form of a multileveled package statement is
• package pkg1[.pkg2[.pkg3]];
• A package hierarchy must be reflected in thee file system of your Java
development system.
• Example package java.awt.image needs to be stored in java\awt\
image in a windows environment.
Finding Packages and ClassPATH
• What is ClassPath
• a classpath is a path for the compiler to identify which class, or which
package we use in our defined class.
• It provides the compiler a way to find classes or packages that are
used in our class.
• Packages

• It is a logical container of classes, interfaces, and sub-packages. A
package provides a unique space for classes and provides a scope for
classes and interfaces.

• A class is associated with a package using the following.
• There are three ways how java run-time system find a
package in Java program.
First: By default the java run-time system considers the
current directory which you are working as starting
directory and checks for the package defined and finds
it if it is present that directory.
Second: To specify the directory path by setting
the CLASSPATH environment variable.
Third: Using -classpath option while compiling and
running the java program to specify the path to your
classes.
Points !!
• We can have only one
class in Package to be Please note that source file and
public , and other than class file of all the files of package
public are not accessible should be in package only and not
outside so what to do. in root directory.
• We have to create Files can be in different directory
different files within then to deal with them CLASS
same package for each PATH come in action.
public class make
different files.

04/21/2025 SOBUZ 16
Adding a Class to a Package

Every java source file can contain only class declared


as public.
The name of the source file should be same as the
name of the public class with .java extension.

package p1; package p1;


public public ClassB{…………}
ClassA{ ……………}
Source file : Source file: ClassB.java
ClassA.java
Subdirectory:p1
Subdirectory: p1
04/21/2025 S 17
Example1-Package
package p1; import p1.ClassA;
public class ClassA
{ Class testclass
public void displayA( ) {
{ public static void main(String str[])
System.out.println(“Class A”); {
} ClassA obA=new ClassA();
} obA.displayA();
Source file – ClassA.java }
Subdirectory-p1 } Source file-testclass.java
ClassA.Java and ClassA.class->p1 testclass.java and testclass.class->in
a directory of which p1 is
subdirectory.

04/21/2025 18
Creating Packages

Consider the following declaration:


package firstPackage.secondPackage;
This package is stored in subdirectory named
firstPackage.secondPackage.
A java package can’t contain more than one class
definitions that can be declared as public.
Only one of the classes which is declared public and
that class name with .java extension is the source file
name.

04/21/2025 19
Example2-Package
package p2; import p1.ClassA;
public class ClassB import p2.ClassB;
{
protected int m =10; class PackageTest2
{
public void displayB()
public static void main(String str[])
{
{
System.out.println(“Class B”);
ClassA obA=new ClassA();
System.out.println(“m= “+m);
Classb obB=new ClassB();
}
obA.displayA();
} obB.displayB();
}
}

04/21/2025 20
Example 3- Package
import p2.ClassB; class PackageTest3
class ClassC extends ClassB {
{ public static void main(String args[])
int n=20; {
void displayC() ClassC obC = new ClassC();
{ obC.displayB();
System.out.println(“Class C”); obC.displayC();
System.out.println(“m= “+m); }
System.out.println(“n= “+n); }
}
}

04/21/2025 21
Package
package p1; Correct Code:
public class Teacher
{………….}
import p1.*;
public class Student import p2.*;
{……………..}
In Different files
p1.Student student1;
package p2;
public class Courses p2.Student student2;
{………..}
public class Student
{………………..}..Different files
import p1.*;
import p2.*;
Student student1; //Error
04/21/2025 22
Default Package
If a source file does not begin with the package statement, the classes
contained in the source file reside in the default package
The java compiler automatically looks in the default package to find
classes.

04/21/2025 23
Finding Packages
Two ways:
1.By default, java runtime system uses current directory as starting point and
search all the subdirectories for the package.
2.Specify a directory path using CLASSPATH environmental variable.

04/21/2025 24
CLASSPATH Environment Variable
The compiler and runtime interpreter know how to find standard
packages such as java.lang and java.util
The CLASSPATH environment variable is used to direct the compiler
and interpreter to where programmer defined imported packages can
be found
The CLASSPATH environment variable is an ordered list of
directories and files

04/21/2025 25
CLASSPATH Environment Variable

To set the CLASSPATH variable we use the following command:


set CLASSPATH=c:\
Java compiler and interpreter searches the user defined packages from
the above directory.
To clear the previous setting we use:
set CLASSPATH=
Example1-Package[Using CLASSPATH]
package p1; import p1.ClassA;
public class ClassA
{ Class PackageTest1
public void displayA( ) {
{ public static void main(String str[])
System.out.println(“Class A”); {
} ClassA obA=new ClassA();
} obA.displayA();
}}
Source file – c:\p1\ Source file-c:\java\jdk1.6.0_06\bin\
ClassA.java PackageTest1.java
Compile-javac c:\p1\ Compile-javac PackageTest1.java
ClassA.java
Copy –PackageTest1.class -> c:\
04/21/2025 Class file in –c:\p1\ SOBUZ 27
Execute-java PackageTest1
Example2-Package[Using CLASSPATH]
package p2; import p1.*;
public class ClassB import p2.*;
class PackageTest2
{
{
protected int m =10;
public static void main(String str[])
public void displayB() {
{ ClassA obA=new ClassA();
System.out.println(“Class B”); Classb obB=new ClassB();
System.out.println(“m= “+m); obA.displayA();
obB.displayB();} }
}
}
Source file-c:\java\jdk1.6.0_06\
Source file – c:\p2\
bin\PackageTest2.java
ClassB.java
Compile-javac PackageTest2.java
Compile-c:\p2\ClassB.java
Copy –PackageTest2.class -> c:\
Class file in –c:\p2\
04/21/2025
ClassB.class Execute-java PackageTest2
SOBUZ 28
Example 3- Package[Using CLASSPATH]
import p2.ClassB; class PackageTest3
class ClassC extends ClassB {
{ public static void main(String args[])
int n=20; {
void displayC() ClassC obC = new ClassC();
{ obC.displayB();
System.out.println(“Class C”); obC.displayC();
System.out.println(“m= “+m); }
System.out.println(“n= “+n); }
} Source file-c:\java\jdk1.6.0_06\
bin\PackageTest3.java
}
Source file – c:\ClassC.java
Compile-javac PackageTest3.java
Compile-c:\ClassC.java
Copy –PackageTest3.class -> c:\
Class file in –c:\ClassC.class
04/21/2025 Execute-java PackageTest3
SOBUZ 29
Adding a Class to a Package

Every java source file can contain only class declared


as public.
The name of the source file should be same as the
name of the public class with .java extension.

package p1; package p1;


public public ClassB{…………}
ClassA{ ……………}
Source file : Source file: ClassB.java
ClassA.java
Subdirectory:p1
Subdirectory: p1
04/21/2025 S 30
Adding a Class to a Package
1.Decide the name of the package.
2.Create the subdirectory with this name under the
directory where the main source file is located.
3.Create classes to be placed in the package in separate
source files and declare the package statement
package packagename;
4. Compile each source file. When completed the package will
contain .class files of the source files.

04/21/2025 31
public/package/private scope
Scope is concerned with the visibility of program
elements such as classes and members
Class members (methods or instance fields) can be
defined with public, package (default), private or
protected scope
A class has two levels of visibility:
-public scope means it is visible outside its containing
package
- default scope means it is visible only inside the
package. (package scope/ friendly scope)

04/21/2025 32
public/package/private scope
A class member with public scope means it is visible
anywhere its class is visible
A class member with private scope means it is visible only
within its encapsulating class
A class/class member with package scope means it is
visible only inside its containing package
A class member with protected scope means it is visible
every where except the non-subclasses in other package.

04/21/2025 33
Example 1
package my_package;

class A // package scope


{
// A’s public & private
members
}

public class B // public


scope
{
// B’s public and private members
}

04/21/2025 34
Example-2
package my_package;

class D
{
// D’s public & private members

// Class D ‘knows’ about classes A and B

private B b; // OK – class B has


public scope
private A a; // OK – class A has
package scope

04/21/2025 35
Example-3

package another_package;
import my_package.*;

class C
{
// C’s public & private members

// class C ‘knows’ about class B

private B b; // OK – class B has public


scope

04/21/2025 36
Example 4
package my_package;
class A
{
int get() { return data; } // package
scope
public A(int d) { data=d;} // public
scope
private int data;
// private scope
}

class B
{
void f()
{
A a=new A(d); // OK A has package scope
int d=a.get(); // OK – get() has package
scope
04/21/2025
int d1=a.data; SOBUZ // Error! – data is private 37
Levels of Access Control

Np\no

04/21/2025 38
Access Protection in Java
Packages
• You might be aware of various aspects of Java’s access control
mechanism and its access specifiers. Packages in Java add another
dimension to access control. Both classes and packages are a
means of data encapsulation. While packages act as containers for
classes and other subordinate packages, classes act as containers
for data and code. Because of this interplay between packages and
classes, Java packages addresses four categories of visibility for
class members:
• Sub-classes in the same package
• Non-subclasses in the same package
• Sub-classes in different packages
• Classes that are neither in the same package nor sub-classes
No Modifier Protected Public
Private

Same Class Yes Yes Yes Yes

Same Package
No Yes Yes Yes
Subclasses

Same Package Non-


No Yes Yes Yes
Subclasses

Different Packages
No No Yes Yes
Subclasses

Different Packages Non-


No No No Yes
Subclasses
1.Anything declared public can be accessed from anywhere
2.Anything declared private can be seen only within that class
3.If access specifier is not mentioned, an element is visible to
subclasses as well as to other classes in the same package
4.Lastly, anything declared protected element can be seen
outside your current package, but only to classes that subclass
your class directly
• This way, Java packages provide access control to the classes.
Well, this wraps up the concept of packages in Java. Here are
some points that you should keep in mind when using
packages in Java.
• Points to Remember
• Every class is part of some package. If you omit the
package statement, the class names are put into the
default package
• A class can have only one package statement but it can
have more than one import package statements
• The name of the package must be the same as the
directory under which the file is saved
• When importing another package, package declaration
must be the first statement, followed by package import

You might also like