SlideShare a Scribd company logo
1 of 66
Java Packages
Packages are used in Java in-order to prevent
naming conflicts, to control access, to make
searching/locating and usage of classes,
interfaces, enumerations and annotations
easier etc.
A Package can be defined as a grouping of
related types(classes, interfaces,
enumerations and annotations ) providing
access protection and name space
management.
Programmers can define their own packages to
bundle group of classes/interfaces etc. It is a
good practice to group related classes
implemented by you so that a programmers
can easily determine that the classes,
interfaces, enumerations, annotations are
related.
• Since the package creates a new namespace
there won't be any name conflicts with names
in other packages. Using packages, it is easier
to provide access control and it is also easier
to locate the related classed.
Overview
• Every class is part of some package.
• All classes in a file are part of the same
package.
• You can specify the package using a package
declaration:
package name ;
as the first (non-comment) line in the file.
• Multiple files can specify the same package name.
• If no package is specified, the classes in the file go into a
special unnamed package (the same unnamed package for
all files).
• If package name is specified, the file must be in a
subdirectory called name (i.e., the directory name must
match the package name).
• You can access public classes in another (named) package
using:
package-name.class-name
You can access the public fields and methods of such classes
using:
package-name.class-name.field-or-method-name
You can avoid having to include the package-name using:
import package-name.*;
Or
import package-name.class-name;
at the beginning of the file (after the package declaration).
The former imports all of the classes in the package, and the
second imports just the named class. You must still use:
class-name
to access the classes in the packages, and
class-name.field-or-method-name
to access the fields and methods of the class; the only thing
you can leave off is the package name.
Many times when we get a chance to work on a
small project, one thing we intend to do is to
put all java files into one single directory. It is
quick, easy and harmless. However if our
small project gets bigger, and the number of
files is increasing, putting all these files into
the same directory would be a nightmare for
us. In java we can avoid this sort of problem
by using Packages.
• Packages are nothing more than the way we
organize files into different directories
according to their functionality, usability as
well as category they should belong to.
• Basically, files in one directory (or package)
would have different functionality from those
of another directory. For example, files in
java.io package do something related to I/O,
but files in java.net package give us the way to
deal with the Network
. In GUI applications, it's quite common for us to
see a directory with a name "ui" (user
interface), meaning that this directory keeps
files related to the presentation part of the
application. On the other hand, we would see
a directory called "engine", which stores all
files related to the core functionality of the
application instead.
Packaging also help us to avoid class name
collision when we use the same class name as
that of others. For example, if we have a class
name called "Vector", its name would crash
with the Vectorclass from JDK. However, this
never happens because JDK use java.util as a
package name for the Vector class
(java.util.Vector).
• So our Vector class can be named as "Vector"
or we can put it into another package
like com.mycompany.Vector without fighting
with anyone. The benefits of using package
reflect the ease of maintenance, organization,
and increase collaboration among developers.
Understanding the concept of package will
also help us manage and use files stored in jar
files in more efficient ways.
How to create a package
Suppose we have a file called HelloWorld.java,
and we want to put this file in a
package world. First thing we have to do is to
specify the keyword package with the name of
the package we want to use (world in our
case) on top of our source file, before the
code that defines the real classes in the
package, as shown in our HelloWorld class
below:
// only comment can be here
package world;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
• One thing you must do after creating a
package for the class is to create nested
subdirectories to represent package hierachy
of the class. In our case, we have
the world package, which requires only one
directory. So, we create a directory world and
put our HelloWorld.java into it.
Setting up the CLASSPATH
we put the package world under C:
So we just set our CLASSPATH as:
set CLASSPATH=.;C:;
We set the CLASSPATH to point to 2 places, .
(dot) and C: directory.
Note: If you used to play around with DOS or
UNIX, you may be familiar with . (dot) and ..
(dot dot). We use . as an alias for the current
directory and .. for the parent directory. In
our CLASSPATH we include this . for
convenient reason. Java will find our class file
not only from C: directory but from the
current directory as well. Also, we use ;
(semicolon) to separate the directory location
in case we keep class files in many places.
If you do the following:
C:worldjavac HelloWorld.java
If you try to run this HelloWorld using java
HelloWorld, you will get the following error:
• C:world>java HelloWorld Exception in thread "main"
java.lang.NoClassDefFoundError: HelloWorld (wrong name:
world/HelloWorld) at java.lang.ClassLoader.defineClass0(Native
Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:442)
at
java.security.SecureClassLoader.defineClass(SecureClassLoader.java:
101) at
java.net.URLClassLoader.defineClass(URLClassLoader.java:248) at
java.net.URLClassLoader.access$1(URLClassLoader.java:216) at
java.net.URLClassLoader$1.run(URLClassLoader.java:197) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:191) at
java.lang.ClassLoader.loadClass(ClassLoader.java:290) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286) at
java.lang.ClassLoader.loadClass(ClassLoader.java:247)
The reason is right now the HelloWorld class
belongs to the package world. If we want to
run it, we have to tell JVM about its fullyqualified class
name (world.HelloWorld) instead of its plain
class name (HelloWorld).
C:world>java world.HelloWorld
C:world>Hello World
Note: fully-qualified class name is the name
of the java class that includes its package
name
To make this example more understandable,
let's put the HelloWorld class along with its
package (world) be
under C:myclasses directory instead.
• We just changed the location of the package
from C:worldHelloWorld.java to
C:myclassesworldHelloWorld.java.
Our CLASSPATH then needs to be changed to
point to the new location of the
package world accordingly.
set CLASSPATH=.;C:myclasses;
Thus, Java will look for java classes from the
current directory and C:myclasses directory
instead.
Someone may ask "Do we have to run
the HelloWorld at the directory that we store
its class file everytime?". The answer is NO.
We can run the HelloWorld from anywhere as
long as we still include the package world in
the CLASSPATH. For example,
C:>set CLASSPATH=.;
C:; C:>set CLASSPATH // see what we have in
CLSSPATH
CLASSPATH=.;C:;
C:>cd world
C:world>java world.HelloWorld
Hello World
C:world>cd ..
C:>java world.HelloWorld
Hello World
Subpackage
• (package inside another package)
• Assume we have another file
called HelloMoon.java. We want to store it in
a subpackage "moon", which stays inside
package world. The HelloMoon class should
look something like this:
package world.moon;
public class HelloMoon
{
private String name = "rabbit";
public getName() { return name; }

public setName(String name) { this.name = name;
}}
If we store the package world under C: as
before, the HelloMoon.java would be
c:worldmoonHelloMoon.java
Although we add a subpackage under package
world, we still don't have to change anything
in our CLASSPATH. However, when we want to
reference to the HelloMoon class, we have to
useworld.moon.HelloMoon as its fullyqualified class name.
How to use package
There are 2 ways in order to use the public
classes stored in package.
• 1. Declare the fully-qualified class name. For
example,
...
world.HelloWorld helloWorld = new
world.HelloWorld();
world.moon.HelloMoon helloMoon = new
world.moon.HelloMoon();

String name = helloMoon.getName();
...
2) Use an "import" keyword:
import world.*; // we can call any public
classes inside the world package
import world.moon.*; // we can call any
public classes inside the world.moon package
import java.util.*; // import all public classes
//from java.util package
import java.util.Hashtable; // import only
//Hashtable class (not all classes in java.util
//package)
Thus, the code that we use to call the
HelloWorld and HelloMoon class should be
...
HelloWorld helloWorld = new HelloWorld(); //
//don't have to explicitly specify
//world.HelloWorld anymore
HelloMoon helloMoon = new HelloMoon(); //
//don't have to explicitly specify
//world.moon.HelloMoon anymore
...
Note that we can call public classes stored in the
package level we do the import only. We can't
use any classes that belong to the subpackage
of the package we import. For example, if we
import package world, we can use only
the HelloWorld class, but not
the HelloMoon class.
Using classes stored in jar file
Jar files are the place where we put a lot of files
to be together. We compress these files and
make them as a single bundle. Jar files may
also include directories, subdirectories to
represent class and package hierachy.
Normally, we can see what is inside a jar file
by using the command jar -tvf fileName.jar
there is a class called javax.servlet.http.Cookie.
We can call this class by
import javax.servlet.http.Cookie; // import
only Cookie class or import
javax.servlet.http.*; // import the whole
javax.servlet.http package
But we have to include this package in
the CLASSPATH as well.
set CLASSPATH=.;D:JSDK2.0libjsdk.jar;
Note that if the package is stored inside a jar
file, we have to include the jar file with its
extension (.jar) in the CLASSPATH. However, if
the package is a plain directory, we just put
the name of directory into the CLASSPATH.
Using Packages
Using packages
•

In a Java source file, the package that this
file's class or classes belong to is specified
with the package keyword. This keyword is
usually the first keyword in the source file.
package java.awt.event
• To use a package's classes inside a Java source
file, it is convenient to import the classes from
the package with an import declaration. The
following declaration
import java.awt.event.*;

imports all classes from
the java.awt.event package, while the next
declaration
import java.awt.event.ActionEvent;
imports only the ActionEvent class from the
package. After either of these import
declarations, the ActionEvent class can be
referenced using its simple class name:
ActionEvent myEvent = new ActionEvent();
Classes can also be used directly without an
import declaration by using the fully qualified
name of the class. For example,
java.awt.event.ActionEvent myEvent = new
java.awt.event.ActionEvent();
does not require a preceding import
declaration.
Note that if you do not use a package
declaration, your class ends up in an unnamed
package.Classes in an unnamed package
cannot be imported from classes in any other
package.
Package access protection
• Classes within a package can access classes
and members declared with default
access and class members declared with
the protected access modifier. Default access
is enforced when neither
the public, protected nor private access
modifier is specified in the declaration.
• By contrast, classes in other packages cannot
access classes and members declared with
default access. Class members declared
as protected can be accessed from the classes
in the same package as well as classes in other
packages that are subclasses of the declaring
class.
Creation of JAR files
• JAR Files are created with the jar command-line
utility. The command
jar cf myPackage.jar *.class

compresses all .class files into the JAR
file myPackage.jar. The ' c ' option on the
command line tells the jar command to "create
new archive." The ' f ' option tells it to create a
file. The file's name comes next before the
contents of the JAR file.
How the Java Compiler Finds Files
When you compile a file that uses a class (or
interface) that is not defined in the same file,
the Java compiler uses
• the name of the class
• the names of imported packages (if any)
• the name of the current package
to try to locate the class definition. For example,
assume that you are working in directory
Javadir, which contains one file named
Test.java:
import ListPkg.*;
public class Test {
List L; ...
}
Since List is not defined in Test.Java, and since
there is no file List.java in the current
directory, the compiler will look for List.java in
the ListPkg subdirectory (since Test.java
imports the ListPkg package).
Now suppose that the ListPkg subdirectory
contains two files: List.java and ListNode.java,
both part of the ListPkg package. Also assume
that List.java uses the ListNode class defined
in ListNode.java. If you try to compile just
List.java in the ListPkg subdirectory, you will
get an error, because the compiler will try to
find the file ListNode.java in a "ListPkg"
subdirectory of the current directory, rather
than looking in the current directory itself.
There are (at least) three ways to solve this
problem:
• Always compile a package from
the parent directory. For example, compile
List.java from Javadir, rather than from
Javadir/ListPkg; in the Javadir directory, type:
javac ListPkg/List.java
• Always compile all files in a package at the
same time; for example, in the directory
Javadir/ListPkg type:
javac *.java
• Make a circular link from the package
subdirectory to itself; for example, in the
directory Javadir/ListPkg type:
ln -s . ListPkg
The CLASSPATH Environment Variable
To use a package that is not in a subdirectory of
the current directory (i.e., the directory in
which you invoke javac), you must set the
environment variable CLASSPATH to tell the
java compiler where to look.
For example, if there were a List package
in /p/course/cs368-horwitz/public/ListPkg, you
would set CLASSPATH like this:
setenv CLASSPATH .:/p/course/cs368horwitz/public
• Including the dot and the colon before the
directory tells the compiler also to look in the
directory in which the compile is being done.
Note that you should set the CLASSPATH
variable to the parent of the "ListPkg"
subdirectory, not to the ListPkg subdirectory
itself.
Java packages

More Related Content

What's hot

Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 

What's hot (20)

OOP java
OOP javaOOP java
OOP java
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java package
Java packageJava package
Java package
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java features
Java featuresJava features
Java features
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Java interface
Java interfaceJava interface
Java interface
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Java- Nested Classes
Java- Nested ClassesJava- Nested Classes
Java- Nested Classes
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 

Viewers also liked

5.interface and packages
5.interface and packages5.interface and packages
5.interface and packages
Deepak Sharma
 

Viewers also liked (20)

Java packages
Java packagesJava packages
Java packages
 
Java packages
Java packagesJava packages
Java packages
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Java packages and access specifiers
Java packages and access specifiersJava packages and access specifiers
Java packages and access specifiers
 
java packages
java packagesjava packages
java packages
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 
Java packages and access specifiers
Java packages and access specifiersJava packages and access specifiers
Java packages and access specifiers
 
Java - Interfaces & Packages
Java - Interfaces & PackagesJava - Interfaces & Packages
Java - Interfaces & Packages
 
Java packages oop
Java packages oopJava packages oop
Java packages oop
 
5.interface and packages
5.interface and packages5.interface and packages
5.interface and packages
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Data types and operators and statements
Data types and operators and statementsData types and operators and statements
Data types and operators and statements
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
 
Chap1 packages
Chap1 packagesChap1 packages
Chap1 packages
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Packages,interfaces and exceptions
Packages,interfaces and exceptionsPackages,interfaces and exceptions
Packages,interfaces and exceptions
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
exception handling
exception handlingexception handling
exception handling
 

Similar to Java packages

Z blue interfaces and packages (37129912)
Z blue   interfaces and  packages (37129912)Z blue   interfaces and  packages (37129912)
Z blue interfaces and packages (37129912)
Narayana Swamy
 
Unit4 java
Unit4 javaUnit4 java
Unit4 java
mrecedu
 

Similar to Java packages (20)

Packages in java
Packages in javaPackages in java
Packages in java
 
Class notes(week 7) on packages
Class notes(week 7) on packagesClass notes(week 7) on packages
Class notes(week 7) on packages
 
Class notes(week 7) on packages
Class notes(week 7) on packagesClass notes(week 7) on packages
Class notes(week 7) on packages
 
Package In Java
Package In JavaPackage In Java
Package In Java
 
Java packages
Java packagesJava packages
Java packages
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Package in Java
Package in JavaPackage in Java
Package in Java
 
Packages
PackagesPackages
Packages
 
Javapackages 4th semester
Javapackages 4th semesterJavapackages 4th semester
Javapackages 4th semester
 
Java - Packages Concepts
Java - Packages ConceptsJava - Packages Concepts
Java - Packages Concepts
 
Z blue interfaces and packages (37129912)
Z blue   interfaces and  packages (37129912)Z blue   interfaces and  packages (37129912)
Z blue interfaces and packages (37129912)
 
PACKAGES, MULTITHREADED PROGRAMMING & MANAGING ERRORS AND EXCEPTIONS in java
PACKAGES, MULTITHREADED PROGRAMMING & MANAGING ERRORS AND EXCEPTIONS in javaPACKAGES, MULTITHREADED PROGRAMMING & MANAGING ERRORS AND EXCEPTIONS in java
PACKAGES, MULTITHREADED PROGRAMMING & MANAGING ERRORS AND EXCEPTIONS in java
 
javapackage
javapackagejavapackage
javapackage
 
Java basics
Java basicsJava basics
Java basics
 
packages.ppt
packages.pptpackages.ppt
packages.ppt
 
Practice Program-9-Packages-Unit 4.docx
Practice Program-9-Packages-Unit 4.docxPractice Program-9-Packages-Unit 4.docx
Practice Program-9-Packages-Unit 4.docx
 
packages unit 5 .ppt
packages  unit 5 .pptpackages  unit 5 .ppt
packages unit 5 .ppt
 
Unit4 java
Unit4 javaUnit4 java
Unit4 java
 
Packages access protection, importing packages
Packages   access protection, importing packagesPackages   access protection, importing packages
Packages access protection, importing packages
 

More from Shreyans Pathak (7)

Introduction to 8086 microprocessor
Introduction to 8086 microprocessorIntroduction to 8086 microprocessor
Introduction to 8086 microprocessor
 
8051 interrupts
8051 interrupts8051 interrupts
8051 interrupts
 
8051 Timers and Counters
8051 Timers and Counters8051 Timers and Counters
8051 Timers and Counters
 
AVL Trees
AVL TreesAVL Trees
AVL Trees
 
8051 Programming Instruction Set
 8051 Programming Instruction Set 8051 Programming Instruction Set
8051 Programming Instruction Set
 
Introduction state machine
Introduction state machineIntroduction state machine
Introduction state machine
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 

Recently uploaded

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 

Java packages

  • 2. Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier etc.
  • 3. A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations ) providing access protection and name space management.
  • 4. Programmers can define their own packages to bundle group of classes/interfaces etc. It is a good practice to group related classes implemented by you so that a programmers can easily determine that the classes, interfaces, enumerations, annotations are related.
  • 5. • Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classed.
  • 6. Overview • Every class is part of some package. • All classes in a file are part of the same package. • You can specify the package using a package declaration: package name ; as the first (non-comment) line in the file.
  • 7. • Multiple files can specify the same package name. • If no package is specified, the classes in the file go into a special unnamed package (the same unnamed package for all files). • If package name is specified, the file must be in a subdirectory called name (i.e., the directory name must match the package name). • You can access public classes in another (named) package using: package-name.class-name You can access the public fields and methods of such classes using: package-name.class-name.field-or-method-name
  • 8. You can avoid having to include the package-name using: import package-name.*; Or import package-name.class-name; at the beginning of the file (after the package declaration). The former imports all of the classes in the package, and the second imports just the named class. You must still use: class-name to access the classes in the packages, and class-name.field-or-method-name to access the fields and methods of the class; the only thing you can leave off is the package name.
  • 9.
  • 10. Many times when we get a chance to work on a small project, one thing we intend to do is to put all java files into one single directory. It is quick, easy and harmless. However if our small project gets bigger, and the number of files is increasing, putting all these files into the same directory would be a nightmare for us. In java we can avoid this sort of problem by using Packages.
  • 11. • Packages are nothing more than the way we organize files into different directories according to their functionality, usability as well as category they should belong to.
  • 12. • Basically, files in one directory (or package) would have different functionality from those of another directory. For example, files in java.io package do something related to I/O, but files in java.net package give us the way to deal with the Network
  • 13. . In GUI applications, it's quite common for us to see a directory with a name "ui" (user interface), meaning that this directory keeps files related to the presentation part of the application. On the other hand, we would see a directory called "engine", which stores all files related to the core functionality of the application instead.
  • 14. Packaging also help us to avoid class name collision when we use the same class name as that of others. For example, if we have a class name called "Vector", its name would crash with the Vectorclass from JDK. However, this never happens because JDK use java.util as a package name for the Vector class (java.util.Vector).
  • 15. • So our Vector class can be named as "Vector" or we can put it into another package like com.mycompany.Vector without fighting with anyone. The benefits of using package reflect the ease of maintenance, organization, and increase collaboration among developers. Understanding the concept of package will also help us manage and use files stored in jar files in more efficient ways.
  • 16. How to create a package Suppose we have a file called HelloWorld.java, and we want to put this file in a package world. First thing we have to do is to specify the keyword package with the name of the package we want to use (world in our case) on top of our source file, before the code that defines the real classes in the package, as shown in our HelloWorld class below:
  • 17. // only comment can be here package world; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }
  • 18. • One thing you must do after creating a package for the class is to create nested subdirectories to represent package hierachy of the class. In our case, we have the world package, which requires only one directory. So, we create a directory world and put our HelloWorld.java into it.
  • 19. Setting up the CLASSPATH
  • 20. we put the package world under C: So we just set our CLASSPATH as: set CLASSPATH=.;C:; We set the CLASSPATH to point to 2 places, . (dot) and C: directory.
  • 21. Note: If you used to play around with DOS or UNIX, you may be familiar with . (dot) and .. (dot dot). We use . as an alias for the current directory and .. for the parent directory. In our CLASSPATH we include this . for convenient reason. Java will find our class file not only from C: directory but from the current directory as well. Also, we use ; (semicolon) to separate the directory location in case we keep class files in many places.
  • 22. If you do the following: C:worldjavac HelloWorld.java If you try to run this HelloWorld using java HelloWorld, you will get the following error:
  • 23. • C:world>java HelloWorld Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong name: world/HelloWorld) at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:442) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java: 101) at java.net.URLClassLoader.defineClass(URLClassLoader.java:248) at java.net.URLClassLoader.access$1(URLClassLoader.java:216) at java.net.URLClassLoader$1.run(URLClassLoader.java:197) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:191) at java.lang.ClassLoader.loadClass(ClassLoader.java:290) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286) at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
  • 24. The reason is right now the HelloWorld class belongs to the package world. If we want to run it, we have to tell JVM about its fullyqualified class name (world.HelloWorld) instead of its plain class name (HelloWorld).
  • 25. C:world>java world.HelloWorld C:world>Hello World Note: fully-qualified class name is the name of the java class that includes its package name
  • 26. To make this example more understandable, let's put the HelloWorld class along with its package (world) be under C:myclasses directory instead.
  • 27. • We just changed the location of the package from C:worldHelloWorld.java to C:myclassesworldHelloWorld.java. Our CLASSPATH then needs to be changed to point to the new location of the package world accordingly. set CLASSPATH=.;C:myclasses;
  • 28. Thus, Java will look for java classes from the current directory and C:myclasses directory instead.
  • 29. Someone may ask "Do we have to run the HelloWorld at the directory that we store its class file everytime?". The answer is NO. We can run the HelloWorld from anywhere as long as we still include the package world in the CLASSPATH. For example,
  • 30. C:>set CLASSPATH=.; C:; C:>set CLASSPATH // see what we have in CLSSPATH CLASSPATH=.;C:; C:>cd world
  • 31. C:world>java world.HelloWorld Hello World C:world>cd .. C:>java world.HelloWorld Hello World
  • 32. Subpackage • (package inside another package) • Assume we have another file called HelloMoon.java. We want to store it in a subpackage "moon", which stays inside package world. The HelloMoon class should look something like this:
  • 33. package world.moon; public class HelloMoon { private String name = "rabbit"; public getName() { return name; } public setName(String name) { this.name = name; }}
  • 34. If we store the package world under C: as before, the HelloMoon.java would be c:worldmoonHelloMoon.java
  • 35. Although we add a subpackage under package world, we still don't have to change anything in our CLASSPATH. However, when we want to reference to the HelloMoon class, we have to useworld.moon.HelloMoon as its fullyqualified class name.
  • 36. How to use package There are 2 ways in order to use the public classes stored in package.
  • 37. • 1. Declare the fully-qualified class name. For example, ... world.HelloWorld helloWorld = new world.HelloWorld(); world.moon.HelloMoon helloMoon = new world.moon.HelloMoon(); String name = helloMoon.getName(); ...
  • 38. 2) Use an "import" keyword: import world.*; // we can call any public classes inside the world package import world.moon.*; // we can call any public classes inside the world.moon package
  • 39. import java.util.*; // import all public classes //from java.util package import java.util.Hashtable; // import only //Hashtable class (not all classes in java.util //package)
  • 40. Thus, the code that we use to call the HelloWorld and HelloMoon class should be
  • 41. ... HelloWorld helloWorld = new HelloWorld(); // //don't have to explicitly specify //world.HelloWorld anymore HelloMoon helloMoon = new HelloMoon(); // //don't have to explicitly specify //world.moon.HelloMoon anymore ...
  • 42. Note that we can call public classes stored in the package level we do the import only. We can't use any classes that belong to the subpackage of the package we import. For example, if we import package world, we can use only the HelloWorld class, but not the HelloMoon class.
  • 43. Using classes stored in jar file Jar files are the place where we put a lot of files to be together. We compress these files and make them as a single bundle. Jar files may also include directories, subdirectories to represent class and package hierachy. Normally, we can see what is inside a jar file by using the command jar -tvf fileName.jar
  • 44. there is a class called javax.servlet.http.Cookie. We can call this class by import javax.servlet.http.Cookie; // import only Cookie class or import javax.servlet.http.*; // import the whole javax.servlet.http package
  • 45. But we have to include this package in the CLASSPATH as well. set CLASSPATH=.;D:JSDK2.0libjsdk.jar;
  • 46. Note that if the package is stored inside a jar file, we have to include the jar file with its extension (.jar) in the CLASSPATH. However, if the package is a plain directory, we just put the name of directory into the CLASSPATH.
  • 48. Using packages • In a Java source file, the package that this file's class or classes belong to is specified with the package keyword. This keyword is usually the first keyword in the source file. package java.awt.event
  • 49. • To use a package's classes inside a Java source file, it is convenient to import the classes from the package with an import declaration. The following declaration import java.awt.event.*; imports all classes from the java.awt.event package, while the next declaration
  • 50. import java.awt.event.ActionEvent; imports only the ActionEvent class from the package. After either of these import declarations, the ActionEvent class can be referenced using its simple class name: ActionEvent myEvent = new ActionEvent();
  • 51. Classes can also be used directly without an import declaration by using the fully qualified name of the class. For example, java.awt.event.ActionEvent myEvent = new java.awt.event.ActionEvent(); does not require a preceding import declaration.
  • 52. Note that if you do not use a package declaration, your class ends up in an unnamed package.Classes in an unnamed package cannot be imported from classes in any other package.
  • 53. Package access protection • Classes within a package can access classes and members declared with default access and class members declared with the protected access modifier. Default access is enforced when neither the public, protected nor private access modifier is specified in the declaration.
  • 54. • By contrast, classes in other packages cannot access classes and members declared with default access. Class members declared as protected can be accessed from the classes in the same package as well as classes in other packages that are subclasses of the declaring class.
  • 55. Creation of JAR files • JAR Files are created with the jar command-line utility. The command jar cf myPackage.jar *.class compresses all .class files into the JAR file myPackage.jar. The ' c ' option on the command line tells the jar command to "create new archive." The ' f ' option tells it to create a file. The file's name comes next before the contents of the JAR file.
  • 56.
  • 57. How the Java Compiler Finds Files When you compile a file that uses a class (or interface) that is not defined in the same file, the Java compiler uses • the name of the class • the names of imported packages (if any) • the name of the current package
  • 58. to try to locate the class definition. For example, assume that you are working in directory Javadir, which contains one file named Test.java: import ListPkg.*; public class Test { List L; ... }
  • 59. Since List is not defined in Test.Java, and since there is no file List.java in the current directory, the compiler will look for List.java in the ListPkg subdirectory (since Test.java imports the ListPkg package).
  • 60. Now suppose that the ListPkg subdirectory contains two files: List.java and ListNode.java, both part of the ListPkg package. Also assume that List.java uses the ListNode class defined in ListNode.java. If you try to compile just List.java in the ListPkg subdirectory, you will get an error, because the compiler will try to find the file ListNode.java in a "ListPkg" subdirectory of the current directory, rather than looking in the current directory itself.
  • 61. There are (at least) three ways to solve this problem: • Always compile a package from the parent directory. For example, compile List.java from Javadir, rather than from Javadir/ListPkg; in the Javadir directory, type: javac ListPkg/List.java
  • 62. • Always compile all files in a package at the same time; for example, in the directory Javadir/ListPkg type: javac *.java • Make a circular link from the package subdirectory to itself; for example, in the directory Javadir/ListPkg type: ln -s . ListPkg
  • 63. The CLASSPATH Environment Variable To use a package that is not in a subdirectory of the current directory (i.e., the directory in which you invoke javac), you must set the environment variable CLASSPATH to tell the java compiler where to look.
  • 64. For example, if there were a List package in /p/course/cs368-horwitz/public/ListPkg, you would set CLASSPATH like this: setenv CLASSPATH .:/p/course/cs368horwitz/public
  • 65. • Including the dot and the colon before the directory tells the compiler also to look in the directory in which the compile is being done. Note that you should set the CLASSPATH variable to the parent of the "ListPkg" subdirectory, not to the ListPkg subdirectory itself.