Object Oriented Concepts -18CS45
Module -3
Packages & Interfaces
Packages in JAVA
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form,
built-in package and
user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
The package keyword is used to create a package in java.
//save as [Link]
package mypack;
public class Simple
{
public static void main(String args[])
{
[Link]("Welcome to package");
}
}
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
3. fully qualified name.
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 1
Object Oriented Concepts -18CS45
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Example of package that import the packagename.*
//save by [Link]
package pack;
public class A
{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
Output: Hello
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
Example of package by import [Link]
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 2
Object Oriented Concepts -18CS45
//save by [Link]
package pack;
public class A
{
public void msg()
{
[Link]("Hello");
}
}
//save by [Link]
package mypack;
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
Output: Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. [Link] and [Link] packages
contain Date class.
Example of package by import fully qualified name
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 3
Object Oriented Concepts -18CS45
//save by [Link]
package pack;
public class A
{
public void msg()
{
[Link]("Hello");
}
}
//save by [Link]
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A(); //using fully qualified name
[Link]();
}
}
Output: Hello
Access Modifiers/Specifiers
The access modifiers in java specify accessibility (scope) of a data member, method, constructor
or class.
There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 4
Object Oriented Concepts -18CS45
1) private access modifier The private access modifier is accessible only within class.
2) default access modifier If you don't use any modifier, it is treated as default by default.
The default modifier is accessible only within package.
3) protected access modifier
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class
4) public access modifier The public access modifier is accessible everywhere. It has
the widest scope among all other modifiers.
Understanding all java access modifiers by a simple table.
Access within class within outside outside
Modifier package package by package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Interface in java
An interface in java is a blueprint of a class. It has static final variables and abstract
methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract
methods in the java interface does not contain method body. It is used to achieve
abstraction and multiple inheritance in Java.
It cannot be instantiated just like abstract class.
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 5
Object Oriented Concepts -18CS45
Interface fields are public, static and final by default, and methods are public and
abstract.
There are mainly three reasons to use interface. They are given below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.
import [Link];
interface client
{
void input(); // public+abstract
void output();
int a=10; // public, static,final
}
class Giri implements client
{
String name; double sal;
public void input()
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 6
Object Oriented Concepts -18CS45
{
Scanner r = new Scanner([Link]);
[Link]("enter ur name:");
name = [Link]();
[Link]("enter ur sal:");
sal= [Link]();
//a=300;
}
public void output()
{
[Link]("Name:"+name +" "+"Sal:"+sal);
}
public static void main(String[] args)
{
client c = new Giri();
[Link]();
[Link]();
}
}
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 7
Object Oriented Concepts -18CS45
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.
Example
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class Pgm2 implements Printable,Showable
{
public void print()
{
[Link]("Hello");
}
public void show()
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 8
Object Oriented Concepts -18CS45
{
[Link]("Welcome");
}
}
Class InterfaceDemo
{
public static void main(String args[])
{
Pgm2 obj = new Pgm2 ();
[Link]();
[Link]();
}
}
Output:
Hello
Welcome
Multiple inheritance is not supported through class in java but it is
possible by interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in
case of class because of ambiguity.
But it is supported in case of interface because there is no ambiguity as implementation is
provided by the implementation class. For example:
Example
interface Printable
{
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 9
Object Oriented Concepts -18CS45
void print();
}
interface Showable
{
void print();
}
class InterfacePgm1 implements Printable, Showable
{
public void print()
{
[Link]("Hello");
}
}
class InterfaceDemo
{
public static void main(String args[])
{
InterfacePgm1 obj = new InterfacePgm1 ();
[Link]();
}
}
Output:
Hello
As you can see in the above example, Printable and Showable interface have same methods but
its implementation is provided by class TestTnterface1, so there is no ambiguity
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 10
Object Oriented Concepts -18CS45
Multi-threaded Programming
Thread
A thread is a lightweight sub process, a smallest unit of processing.
It is a separate path of execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads.
It shares a common memory area
Java provides built-in support for multithreaded programming. A multithreaded
program contains two or more parts that can run concurrently. Each part of such a program is
called a thread, and each thread defines a separate path of execution. Thus, multithreading is a
specialized form of multitasking.
Multithreading enables you to write very efficient programs that make maximum use
of the CPU, because idle time can be kept to a minimum. Multitasking threads require less
overhead than multitasking processes.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
to utilize the CPU. Multitasking can be achieved by two ways:
Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
Each process has its own address in memory i.e. each process allocates separate memory
area.
Process is heavyweight.
Cost of communication between the processes is high.
Switching from one process to another require some time for saving and loading registers,
memory maps, updating lists etc.
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 11
Object Oriented Concepts -18CS45
Less efficient
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
Thread is lightweight.
Cost of communication between the threads is low.
Highly efficient
An instance of Thread class is just an object, like any other object in java. But a thread of
execution means an individual "lightweight" process that has its own call stack. In java each
thread has its own call stack
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 12
Object Oriented Concepts -18CS45
Thread Lifecycle
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1) New: The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2) Runnable: When we call start() function on Thread object, it’s state is changed to
Runnable. The control is given to Thread scheduler to finish its execution. Whether to run
this thread instantly or keep it in runnable thread pool before running, depends on the OS
implementation of thread scheduler.
3) Running: When thread is executing, it’s state is changed to Running. Thread scheduler
picks one of the thread from the runnable thread pool and change its state to Running.
Then CPU starts executing this thread. A thread can change state to Runnable, Dead or
Blocked from running state depends on time slicing, thread completion of run() method or
waiting for some resources.
4) Blocked / Waiting: This is the state when the thread is still alive, but is currently not
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 13
Object Oriented Concepts -18CS45
eligible to run. Waiting − Sometimes, a thread transitions to the waiting state while the
thread waits for another thread to perform a task. A thread transitions back to the runnable
state, only when another thread signals the waiting thread to continue its execution.
5) Terminated: A thread is in terminated or dead state when its run() method exits.
The Main Thread
When a Java program starts up, one thread begins running immediately. This is usually called
the main thread of your program, because it is the one that is executed when your program
begins.
The main thread is important for two reasons:
It is the thread from which other ―child threads will be spawned(create many threads).
Often, it must be the last thread to finish execution because it performs various
shutdown actions.
Although the main thread is created automatically when your program is started, it can be
controlled through a Thread object. To do so, you must obtain a reference to it by calling the
method currentThread( ), which is a public static member of Thread.
The Thread class defines several methods that help manage threads (shown below)
Method Description
String getName() Retrieves the name of running thread in the current context in String
format
void start() This method will start a new thread of execution by calling run() method
of Thread/runnable object.
setName(String) Set a new name for the thread
currentThread() Returns the name of the current thread under execution
void run() This method is the entry point of the thread. Execution of thread starts
from this method.
void sleep(int This method suspend the thread for mentioned time duration in
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 14
Object Oriented Concepts -18CS45
sleeptime) argument(sleeptime in ms)
void join() This method used to queue up a thread in execution. Once called on
thread, current thread will wait till calling thread completes its execution
class MyThread extends Thread
{
public static void main(String[] args)
{
Thread t = new Thread();
[Link]([Link]());
[Link]([Link]());
[Link]("Girish");
[Link]([Link]());
[Link]([Link]());
Thread t1 = new Thread();
[Link]([Link]());
[Link]([Link]());
[Link]("Kumar");
[Link]([Link]());
[Link]([Link]());
}
}
There are two ways to create thread in java:
Implement the Runnable interface ([Link])
By Extending the Thread class ([Link])
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 15
Object Oriented Concepts -18CS45
Extending Thread class
Creates a thread by a new class that extends Thread class. This creates an instance of that
[Link] extending class must override run() method which is the entry point of new thread.
class MyThread extends Thread
{
public void run()
{
[Link]("thread is running...");
}
public static void main(String args[])
{
MyThread t1=new MyThread();
[Link]();
}
}
Output:
thread is running
Example program using sleep()
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<=10;i++)
[Link]("Child thread");
}
}
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t = new MyThread();
[Link]();
try
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 16
Object Oriented Concepts -18CS45
{
for(int i=0;i<=10;i++)
{
[Link]("parent thread");
[Link](100);
}
}
catch(InterruptedException e)
{
[Link](" Exception occurred");
}
}
}
[Link] class provides the join() method which allows one thread to wait until another
thread completes its execution. If t is a Thread object whose thread is currently executing,
then [Link]() will make sure that t is terminated before the next instruction is executed by the
program.
If there are multiple threads calling the join() methods that means overloading on join allows the
programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for
timing, so you should not assume that join will wait exactly as long as you specify.
There are three overloaded join functions.
join(): It will put the current thread on wait until the thread on which it is called is dead. If thread
is interrupted, then it will throw InterruptedException.
Example program using join()
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<=10;i++)
[Link]("Child thread");
}
}
class ThreadDemo1
{
public static void main(String[] args) throws
InterruptedException
{
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 17
Object Oriented Concepts -18CS45
MyThread t = new MyThread();
[Link]();
for(int i=0;i<=10;i++)
{
[Link]("parent thread");
}
MyThread t1 = new MyThread();
[Link]();
[Link]();
for(int i=0;i<=10;i++)
{
[Link]("parent thread11");
}
}
}
Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable interface.
You can construct a thread on any object that implements Runnable. To implement Runnable, a
class need only implement a single method called run( ), which is declared like this:
public void run( )
run( ) establishes the entry point for another, concurrent thread of execution within your
program. This thread will end when run( ) returns.
Thread defines several constructors.
Thread(Runnable threadOb)
In this constructor, threadOb is an instance of a class that implements the Runnable interface.
This defines where execution of the thread will begin. After the new thread is created, it will not
start running until you call its start( ) method, which is declared within Thread.
In essence, start( ) executes a call to run( ).
The start( ) method is shown here:
class MyThread implements Runnable
{
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 18
Object Oriented Concepts -18CS45
public void run()
{
for(int i=0;i<=10;i++)
[Link]("Child thread");
}
}
class ThreadInterface
{
public static void main(String[] args)
{
MyThread r = new MyThread();
Thread t = new Thread(r);// passing object
[Link]();
for(int i=0;i<=10;i++)
[Link]("Main thread");
}
}
Thread Priorities
Thread priorities are used by the thread scheduler to decide when each thread should be
allowed to run. In theory, higher-priority threads get more CPU time than lower-priority
threads. In practice, the amount of CPU time that a thread gets often depends on several
factors besides its priority. To set a thread’s priority, use the setPriority( ) method, which is a
member of Thread. This is its general form:
final void setPriority(int level)
Here, level specifies the new priority setting for the calling thread. The value of level must be
within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10,
respectively. To return a thread to default priority, specify NORM_PRIORITY, which is currently
5. These priorities are defined as static final variables within Thread. You can obtain the current
priority setting by calling the getPriority( ) method of Thread, shown here:
final int getPriority( )
The following example demonstrates two threads at different priorities, One thread is set two
levels above the normal priority, as defined by Thread.NORM_PRIORITY, and the other is set
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 19
Object Oriented Concepts -18CS45
to two levels below it. The threads are started and allowed to run for ten seconds. Each thread
executes a loop, counting the number of iterations. After ten seconds, the main thread stops both
threads. The number of times that each thread made it through the loop is then displayed.
class MyThread extends Thread
{
public void run()
{
[Link]([Link]().getName());
[Link]([Link]().getPriority());
}
}
class MainThread
{
public static void main(String[] args)
{
MyT t1 = new MyT();
[Link]([Link]().getName());
[Link]([Link]().getPriority());
[Link]("t1 thread");
[Link](10);
[Link]([Link]().getPriority());
[Link]();
}
}
Synchronization
At times when more than one thread try to access a shared resource, we need to ensure that
resource will be used by only one thread at a time. The process by which this is achieved is
called synchronization. The synchronization keyword in java creates a block of code referred
to as critical section.
Key to synchronization is the concept of the monitor. A monitor is an object that is
used as a mutually exclusive lock. Only one thread can own a monitor at a given time. When a
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 20
Object Oriented Concepts -18CS45
thread acquires a lock, it is said to have entered the monitor. All other threads attempting to
enter the locked monitor will be suspended until the first thread exits the monitor. These other
threads are said to be waiting for the monitor.
Thread Synchronization & Mutual Exclusive
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
Method level Synchronization
If you declare any method as synchronized, it is known as synchronized method. Synchronized
method is used to lock an object for any shared resource. When a thread invokes a
synchronized method, it automatically acquires the lock for that object and releases it when the
thread completes its task.
class Table
{
synchronized void printTable(int n)
{
for(int i=1;i<=10;i++)
[Link](n*i);
}
}
class Thread1 extends Thread
{
Table t;
Thread1(Table t)
{
this.t=t;
}
public void run()
{
[Link](5);
}
}
class Thread2 extends Thread
{
Table t;
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 21
Object Oriented Concepts -18CS45
Thread2(Table t)
{
this.t=t;
}
public void run()
{
[Link](7);
}
}
class MainTable
{
public static void main(String[] args)
{
Table obj = new Table(); //only 1 lock can be given to
only 1 thread at a time
Thread1 t1 = new Thread1(obj);
Thread2 t2 = new Thread2(obj);
[Link](); [Link]();
}
}
Block level Synchronization
In block level synchronization the entire method is not yet synchronized only the part of the
method get synchronized, we have to enclosed those few lines of the code put inside
synchronized block
public void show()
{
synchronized(this)
{
……………
……………
}
}
Example
class Table
{
void printTable(int n)
{
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 22
Object Oriented Concepts -18CS45
[Link]("hellooooo");
synchronized(this)
{
for(int i=1;i<=10;i++)
[Link](n*i);
}
[Link]("how r u.......");
}
}
class Thread1 extends Thread
{
Table t;
Thread1(Table t)
{
this.t=t;
}
public void run()
{
[Link](5);
}
}
class Thread2 extends Thread
{
Table t;
Thread2(Table t)
{
this.t=t;
}
public void run()
{
[Link](7);
}
}
class MainTable
{
public static void main(String[] args)
{
Table obj = new Table(); //only 1 lock can be given to
only 1 thread at a time
Thread1 t1 = new Thread1(obj);
Thread2 t2 = new Thread2(obj);
[Link](); [Link]();
[Link]("Thread T is alive: "+ [Link]());
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 23
Object Oriented Concepts -18CS45
}
}
Inter Thread Communication
Inter-thread communication in Java is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed.
Java uses three methods, namely, wait(), notify(), and notifyAll(). All these methods belong to
object class as final so that all classes have them. They must be used within a synchronized block
only.
wait(): It tells the calling thread to give up the lock and go to sleep until some other thread
enters the same monitor and calls notify().
notify(): It wakes up one single thread called wait() on the same object. It should be noted
that calling notify() does not give up a lock on a resource.
notifyAll(): It wakes up all the threads called wait() on the same object.
class InterThread
{
public static void main(String[] args) throws
InterruptedException
{
Thread1 t = new Thread1();
[Link]();
synchronized(t)
{
[Link]("main thread will call wait()");
[Link]();
[Link]("main thread finished waiting after getting
notify");
[Link]([Link]);
}
}
}
class Thread1 extends Thread
{
int total=0;
public void run()
{
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 24
Object Oriented Concepts -18CS45
synchronized(this)
{
[Link]("child thread starts execution");
for(int i=1;i<=100;i++)
{
total = total + i;
}
[Link]("child thread giving notification");
[Link]();
}
}
}
Bounded Buffer Problem
Bounded buffer problem, which is also called producer consumer problem, is one of the
classic problems of synchronization.
Problem Statement:
There is a buffer of n slots and each slot is capable of storing one unit of data. There are two
processes running, namely, producer and consumer, which are operating on the buffer.
A producer tries to insert data into an empty slot of the buffer. A consumer tries to remove data
from a filled slot in the buffer. As you might have guessed by now, those two processes won’t
produce the expected output if they are being executed concurrently.
There needs to be a way to make the producer and consumer work in an independent manner.
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 25
Object Oriented Concepts -18CS45
class Q
{
int num;
boolean value=false;
synchronized void put(int num)
{
while(value)
{
try { wait(); } catch(Exception e) { }
}
[Link]("Put:"+num);
[Link]=num;
value=true;
notify();
}
synchronized void get()
{
while(!value)
{
try { wait(); } catch(Exception e) { }
}
[Link]("Get:"+num);
value=false;
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
Thread t = new Thread(this,"Producer");
[Link]();
}
public void run()
{
int i=0;
while(true)
{
[Link](i++);
try{[Link](100); } catch(Exception e) { }
}
}
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 26
Object Oriented Concepts -18CS45
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
Thread t = new Thread(this,"Consumer");
[Link]();
}
public void run()
{
while(true)
{
[Link]();
try{[Link](1000); } catch(Exception e) { }
}
}
}
class InterThread
{
public static void main(String args[])
{
Q q =new Q();
new Producer(q);
new Consumer(q);
[Link]("Press CTRL + C to stop");
}
}
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 27
Object Oriented Concepts -18CS45
Questions
1. What is package? Explain with example how to create packages in JAVA
2. What are access modifiers? Explain with example the types of modifiers in
JAVA
3. What are interfaces? Explain how interfaces can be implemented in JAVA
[Link] is multi-tasking? Differentiate between Multiprocessing and
multithreading.
5. What is thread? Explain thread life cycle in JAVA
6. List the built-in methods of Thread class with example program
7. Explain how multiple threads can be created and implemented
8. Explain thread priorities with example program in JAVA
9. What is synchronization? Explain with example program in JAVA
[Link] inter thread communication with example program in JAVA
11. What is Bounded Buffer Problem? Explain with example program in JAVA
************************End of Module – 3**************************
Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 28