Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 29

Department of Computer

Science and Engineering

Module II

Package in Java
Presented by: Dr. Ram Paul Hathwal

Dept of CSE, ASET, AUUP


Review Department of Computer
Science and Engineering

Classes contain variables and methods.

We can turn these into objects containing data and methods.

We can limit who sees these using:


public: everyone can use it.
private: only the code in the class can use it.
protected: only inheriting code can use it.

We can also set them as static – meaning we can use the methods without making an
object.
Review Department of Computer
Science and Engineering

We can turn (super)classes into subclasses.


e.g. a Point class can be used to make a Land class.

Subclasses invisibly pick up all the superclass code and can use the public bits.

Alternatively we can use Interfaces, which are a set of promises.


extends: you get everything.
implements: you promise everything.

If a method expects a parent type, it can take a subclass in, but can only use parent
methods and variables.
Java Packages Department of Computer
Science and Engineering

A Package is a logical organization of related classes. The Java classes can


be logically organized into packages. Grouping is based on functionality.

Java code has hierarchical structure. Packages acts as “containers” for


classes, interfaces or subpackages.

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.
Why Packages? Department of Computer
Science and Engineering

Reusability: Reusability of code is one of the most important requirements in the


software industry.
Reusability saves time, effort and also ensures consistency.
When we name a program , we name it by class name…
Now, how many different names do we need and how difficult to remember them?
If we could put them separated in different folders things would become easy !!
 For it packages are used …..

 Packages allow us to use other people’s code.


 Saves name clashes with other people.
 Note that directories (packages) can’t just start with numbers.
 All package names and directories should be lowercase. 5
Benefits of using Packages Department of Computer
Science and Engineering

In packages, classes can be unique


compared with classes in other
packages.
Handles name conflicts as hierarchy
is used.
Provides a way to hide classes.
Separates design from coding.
The classes contained in the packages
of other programs can be reused.
Packages provides a way to hide
classes.
Types of Java Packages Department of Computer
Science and Engineering

Two types of packages:


1. Java API packages: The already defined package
2. User defined packages: that we create

Java API Packages:


A large number of classes grouped into different
packages based on functionality.
Examples:
1. java.lang
2. java.util
3. java.io
4. java.awt
5.java.net
6.java.applet etc.
Department of Computer
Java API Packages Science and Engineering

java.lang: Contains language support classes (e.g


classes which defines primitive data types, math
operations). This package is automatically imported.
java.io: Contains classes for supporting input /
output operations.
java.util: Contains utility classes like vectors,
hash tables, random numbers etc.
java.applet: Contains classes for creating Applets.
java.awt: Contain classes for implementing the
components for graphical user interfaces.
java.net: Contain classes for supporting networking
operations.
Importing Package Department of Computer
Science and Engineering

//Java is package and util is


subpackage
import java.util.*
//import the Scanner class from
util package
import java.util.Scanner;
// import all the classes from user
defined package
import userDefinedPack.*;
Static import Department of Computer
Science and Engineering

import static packageName.className.*;

Example:
import static java.lang.Math.*;
...
double angle = sin(PI / 2) + ln(E * E);

Static import allows you to refer to the members of another class without writing
that class's name.
Should be used rarely and only with classes whose contents are entirely static
"utility" code.
Referring to Packages Department of Computer
Science and Engineering

packageName.className

Example:
java.util.Scanner console =
new java.util.Scanner(java.lang.System.in);

You can use a type from any package without importing it if you write its full name.
Sometimes this is useful to disambiguate similar names.
◦ Example: java.awt.List and java.util.List
◦ Or, explicitly import one of the classes.
The default Package Department of Computer
Science and Engineering

Compilation units (files) that do not declare a package are put into a default,
unnamed, package.
Classes in the default package:
 Cannot be imported
 Cannot be used by classes in other packages

Many editors discourage the use of the default package.


Package java.lang is implicitly imported in all programs by default.
 import java.lang.*;
How to Access a Package Department of Computer
Science and Engineering

Defining a Package:
 This statement should be used in the beginning of the program to include that program
in that particular package.
package <package name>;
 The package keyword is used to create a package in java.
To Compile: javac -d directory JavaFileName.java
javac -d C:/javaprograms JavaPackages.java
To Run: java packageName.ClassName
java javaprograms.JavaPackages
 The -d switch specifies the destination where to put the generated class file
 If you want to keep the package within the same directory, you can use . (dot).
Package Access Control Department of Computer
Science and Engineering

Java provides the following access modifiers:


 public: Visible to all other classes.
 private: Visible only to the current class (and any nested types).
 protected: Visible to the current class, any of its subclasses, and any other types within the
same package.
 default (package): Visible to the current class and any other types within the same package.
• Usually referred to as “Friendly”.

To give a member default scope, do not write a modifier:


package pacman.model;
public class Sprite {
int points; // visible to pacman.model.*
String name; // visible to pacman.model.*
User Defined Packages Department of Computer
Science and Engineering

JAVA uses file system to Package names are case The classes declared
manage packages, with sensitive. within the package
each package stored in its The directory name and directory will belong to
own directory. the package name should the specified package.
be the same.
Department of Computer
Steps to create Package Science and Engineering

1. Create a package(folder) named p1.


2. Create a file
named MyCalculator.java inside p1 package.
3. Write the code in MyCalculator.java file.
4. Create a file
named TestPackage.java outside p1 package.
5. Write the following code
in TestPackage.java file.
6. Compile and Run TestPackage.java and get
the output.
Packages Hierarchy in Java Department of Computer
Science and Engineering
Accessing Classes in a Package Department of Computer
Science and Engineering

1. Fully Qualified class name:


Example: java.awt.Color
2. import packagename.classname;
Example: import java.awt.Color;
or
import packagename.*;
Example: import java.awt.*;
 Import statement must appear at the top of the file,
before any class declaration.
18
Adding a Class to a Package Department of Computer
Science and Engineering

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.
 To put a class into a package, one uses the "package" statement:

 The package statement MUST be the first line of code within the file.
 It can be proceeded by comments.

package p1; package p1;

public ClassA{ ……………} public ClassB{…………}


Source file : ClassA.java Source file: ClassB.java
Subdirectory: p1 Subdirectory:p1
19
Department of Computer
Example1-Package Science and Engineering

import p1.ClassA;
package p1;
Class testclass
public class ClassA
{
{
public static void main(String str[])
public void displayA( )
{ {
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.
20
Department of Computer
Example2-Package Science and Engineering

package p2; import p1.ClassA;


public class ClassB import p2.ClassB;
{
class PackageTest2
protected int m =10;
{
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();
}
}
21
Example 3- Package Department of Computer
Science and Engineering

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);
}
}
}
22
Department of Computer
Science and Engineering

//MyCalculator.java //TestPackage.java
package p1;
import p1.MyCalculator;
public class MyCalculator{
class TestPackage{
public int Add(int x,int y)
{ public static void main(String[] args)
return x+y; {
} MyCalculator M = new MyCalculator();
public int Subtract(int x,int y)
System.out.print("\n\n\tThe Sum is : " + M.Add(45,10));
{
return x-y;
System.out.print("\n\n\tThe Subtract is :" +
M.Subtract(45,10));
}
public int Product(int x,int y) System.out.print("\n\n\tThe Product is :" +
{
M.Product(45,10));
return x*y; }
}} }
Package exercise Department of Computer
Science and Engineering

Add packages to the Rock-Paper-Scissors game.


 Create a package for core "model" data.

 Create a package for graphical "view" classes.

 Any general utility code can go into a default package or into


another named utility (util) package.
 Add appropriate package and import statements so that the types can
use each other properly.
Department of Computer
CLASSPATH Science and Engineering

The "root" directory of the package hierarchy is determined by your class path or the
directory from which Java was run.We set the environmental variable ‘CLASSPATH’.
Environmental variables are just variables all computers keep which store user preferences.
You can tell the ‘javac’ and ‘java’ programs the classpath using…

javac –classpath path; path; File.java

set CLASSPATH=.;C:\
The CLASSPATH is a variable that contains a list of directories which are separated by
colons (:) and under the Windows OS, they are separated by semicolons (;)
The programs will look in any directory listed in the CLASSPATH for the start of
directory trees. One path should be “.” if you want to include the present directory.
Department of Computer
CLASSPATH Science and Engineering

Note that if your code is unpackaged this can become quite complicated, as the
classpath must include the directory your code is running from, and the root of the
hierarchy.
Assuming you are in the latter, you'll need this kind of thing:
javac unpackaged/lazyCode/*.java
java -classpath unpackaged/lazyCode/;. MyClass

What you CAN'T do is this:


java unpackaged/lazyCode/MyClass
The JVM will just assume you're trying to run from a package.
Multiple Classes in a Package Department of Computer
Science and Engineering

 A Java source file can have only //Csum.java


one class declared as public, we import calc.*;
package calc;
cannot put two or more public class MyCalculator{
classes together in a.java file. public class Csum{
public static void main(String args[])
This is because of the restriction public int sum(int x, int y)
that the file name should be same { {
Csum obj=new Csum();
as the name of the public class return (x+y);
Csub obj2=new Csub();
with .java extension. }}
 If we want to multiple classes System.out.println("The sum is : "+
//Csub.java
under consideration are to be package calc; obj.sum(10,20));
declared as public, we have to public class Csub{
store them in separate source public int sub(int x, int y) System.out.println("The difference is : "
{ +obj2.sub(30,20));
files and attach the package
return (x-y); }
statement as the first statement in }
those source files. }
}
Department of Computer
Points to be noted !! Science and Engineering

We can have only one class in Package to be public , and other than
public are not accessible outside so what to do.
 We have to create different files within same package for each public
class make different files.
Please note that source file and class file of all the files of package
should be in package only and not in root directory.
Files can be in different directory then to deal with them CLASS PATH
come in action.
If you import a package, all the classes and interface of that package will
beimported excluding the classes and interfaces of the subpackages.
Hence, you need to import the subpackage as well. 28
Department of Computer
Science and Engineering
End

Thank you…

You might also like