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

Unit II - Packages, Interfaces and Threads

The document discusses key concepts related to packages, interfaces, and threads in Java programming. It covers defining and importing packages, access modifiers, rules for creating packages, and differences between inheritance and packages. It also explains what interfaces are in Java, how to declare an interface, and the relationship between classes and interfaces. The document concludes with sections on exception handling and multithreading concepts in Java like thread priorities and synchronization.

Uploaded by

Arshx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Unit II - Packages, Interfaces and Threads

The document discusses key concepts related to packages, interfaces, and threads in Java programming. It covers defining and importing packages, access modifiers, rules for creating packages, and differences between inheritance and packages. It also explains what interfaces are in Java, how to declare an interface, and the relationship between classes and interfaces. The document concludes with sections on exception handling and multithreading concepts in Java like thread priorities and synchronization.

Uploaded by

Arshx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 77

SUBJECT NAME: Programming in Java

SUBJECT CODE: SITA1301


UNIT 2 PACKAGES, INTERFACES AND THREADS
Introduction to Packages – User Defined Packages - Importing
packages – Access protection – Interfaces – Exception Handling
- Exception Types – Using try, catch, throw, throws and finally –
Multithreading – JavaThreadModel – Main thread – Creating
multiple thread – Thread priorities – Synchronization.
Packages :
• It is a mechanism to encapsulate a group of classes, interfaces and
sub packages.
Syntax :
package package-name;

• Package in java can be categorized in two types,


– Built-in package
E.g. lang, awt, javax, swing, net, io, util, sql etc.
– User-defined package
– E.g. MyPack
Built in Packages :
Difference between Inheritance and package in Java
Both package and Inheritance in Java are used for re-use features.
Some differences between them are given below;

Inheritance concept always used to reuse the feature within the


program between class to class, interface to interface and interface to
class but not accessing the feature across the program..

Package concept is to reuse the feature both within the program and
across the programs between class to class, interface to interface and
interface to class.
 
 
Rules to create user defined package
package statement should be the first statement of any package
program.
Choose an appropriate class name or interface name and whose
modifier must be public.
Any package program can contain only one public class or only one
public interface but it can contain any number of normal classes.
Package program should not contain any main class (that means it
should not contain any main())
modifier of constructor of the class which is present in the package
must be public. (This is not applicable in case of interface because
interface have no constructor.)
The modifier of method of class or interface which is present in the
 
 
Importing packages
Example :

//A.java //B.java
package pack; package mypack;
public class A { import pack.*;
public void msg() { class B {
System.out.println("Hello"); public static void main(String
} args[]) {
} A obj = new A();
obj.msg();
}
}
How to compile & Run java package
To compile : javac -d . A.java 

To Run : java mypack.B

The -d is a switch specifies the destination where to put the


generated class file. i.e. it represents destination. The .
Represents the current folder.
How to access package from another package?

There are three ways to access the package from outside the package.

import package.*;//import pack.*;

import package.classname;//import pack.A;

fully qualified name.// pack.A obj=new pack.A();


Importing packages
Example :

//A.java //B.java
package pack; package mypack;
public class A { import pack.*;
public void msg() { class B {
System.out.println("Hello"); public static void main(String
} args[]) {
} A obj = new A();
obj.msg();
}
}
How to access package from another package?
-import package.classname;
//save by A.java   //save by B.java  
   package mypack;  
package pack;   import pack.A;  
public class A{     class B{  
  public void msg()   public static void main(String a
{System.out.println("Hello");}   rgs[]){  
}      A obj = new A();  
   obj.msg();  
  }  
}
How to access package from another package?
-fully qualified name.
   //save by B.java  
//save by A.java   package mypack;  
package pack;   class B{  
public class A{     public static void main(String arg
  public void msg() s[]){  
{System.out.println("Hello");}      pack.A obj = new pack.A();//
} using fully qualified name  
   obj.msg();  
  }  
}
Access Modifiers
• The access modifiers in java specifies accessibility (scope) of a data
member, method,
constructor or class.
• There are 4 types of access modifiers
– private
– default
– protected
– public
Access Modifiers
• The access modifiers in Java specifies the accessibility or scope of a
field, method, constructor, or class. We can change the access level of
fields, constructors, methods, and class by applying the access modifier
on it. 
Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do not
specify any access level, it will be the default.
Access Modifiers
Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package
and outside the package.
Public access modifier

• The members, methods and classes that are declared public can be
accessed from anywhere.
• This modifier doesn’t put any restriction on the access.
package myAddPack;
public class Add
{
public void sum()
{
int x, y;
x=10;
y=20;
System.out.println("Sum is: "+(x+y));
}
}
package demoPack;
import myAddPack.*;
class AddDemo {
public static void main(String args[])
{
Add obj=new Add();
obj.sum();
}
}
protected access
• The protected access modifier is specified using the keyword protected.
• The methods or data members declared as protected are accessible
within same package or sub classes in the different package.
• It 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.
//Addition.java

package abcpackage;
public class Addition
{
protected int addTwoNumbers(int a, int b)
{
return a+b;
}
}
//Test.java
package xyzpackage;
import abcpackage.*;
class Test extends Addition
{
public static void main(String args[])
{
Test obj = new Test();
System.out.println(obj.addTwoNumbers(11, 22));
}
}
Private
The private access modifier is specified using the keyword private.
• The methods or data members declared as private are accessible
only within the class in which they are declared.
• Any other class of the same package will not be able to access these
members.
• Classes or interface can not be declared as private.
//classA.Java
package pack;
class classA
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
//Sample.java
package myPack;
import pack.*;
public class Sample
{
public static void main(String args[])
{
classA obj=new classA();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Default access modifier

When we do not mention any access modifier, it is called default access


modifier.
The scope of this modifier is limited to the package only.
This means that if we have a class with the default access modifier in a
package, only those classes that are in this package can access this
class. 
Interfaces
• An interface declares a set of methods and their signatures. The
methods that are declared in an interface should not have
implementation codes.
• A Class that makes use of an interface should provide the codes for
the methods declared in that interface.
Interfaces
An interface in Java is a blueprint of a class. It has static constants and
abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can
be only abstract methods in the Java interface, not method body. It is
used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods
and variables. It cannot have a method body.
Interfaces
An interface in Java is a blueprint of a class. It has static constants and
abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can
be only abstract methods in the Java interface, not method body. It is
used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods
and variables. It cannot have a method body.
It cannot be instantiated just like the abstract class.
How to declare an interface?

interface <interface_name>{  
      
    // declare constant fields  
    // declare methods that abstract   
    // by default.  
}
The relationship between classes and interfaces

A class extends another class, an interface extends


another interface, but a class implements an
interface.
Example :
interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");}
public static void main(String
args[]){
A6 obj = new A6();
obj.print();
}
}
Implementing interfaces
Once an interface has been defined, one or more classes can
implement that interface.
 To implement an interface, include the implements clause in a class
definition, and then create the methods defined by the interface.
public interface Pet{
public void test();
}
class Dog implements Pet{
public void test(){
System.out.println("Interface Method Implemented");
}
public static void main(String args[]){
Pet p = new Dog();
p.test();
}
}
Java Interface Example
Interface and Class

Animal Pig
•Interface •Class
implements

MyMainClass
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}

class MyMainClass {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Interface and Class

Bank SBI
•Interface •Class
implements

MyMainClass implements
• classs
PNB
interface Bank{
float rateOfInterest();
}
class SBI implements Bank
{
public float rateOfInterest()
{
return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{
eturn 9.7f;
}
}
class TestInterface2
{
public static void main(String[] args){
Bank b=new SBI();
//Bank b=new PNB();
System.out.println("ROI: "+b.rateOfInterest());
}}
Multiple inheritance in Java by interface

• If a class implements multiple interfaces, or an interface extends


multiple interfaces, it is known as multiple inheritance.
Multiple inheritance in Java by interface
/*More than one Interface ,class and MainClass*/
interface Addition {
int addition(int a,int b);
}
interface Subtraction {
int subtraction(int a,int b);
}
class Calculator implements Addition, Subtraction{
public int addition(int a,int b)
{
return a+b;
}
public int subtraction(int a,int b)
{
return a-b;
}
}
class TestInterface2 {
public static void main(String[] args) {

Calculator calc = new Calculator();


System.out.println("Addition : "+calc.addition(25, 35));
System.out.println("Subtraction : "+calc.subtraction(250, 35));
}
}
Extending interfaces
• One interface can inherit another by use of the keyword extends.
Interface and Class

Addition •Interface
Subtraction •Interface
extends

TestInterface3
implements
• classs
Calculator
Main class
/*More than one Interface ,class and MainClass*/
interface Addition {
int addition(int a,int b);
}
interface Subtraction extends Addition{
int subtraction(int a,int b);
}
class Calculator implements Subtraction{
public int addition(int a,int b)
{
return a+b;
}
public int subtraction(int a,int b)
{
return a-b;
}
}
class TestInterface3 {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Addition : "+calc.addition(25, 35));
System.out.println("Subtraction : "+calc.subtraction(250, 35));
}
}
Interface inheritance

interface Printable{  
void print();  
}  
interface Showable extends Printable{  
void show();  
}  
class InheritInterface implements Showable{  
public void print()
{
System.out.println("Hello");
}  
public void show()
{
System.out.println("Welcome");
}  
public static void main(String args[]){  
InheritInterface  obj = new  InheritInterface();  
obj.print();  
obj.show();  
 }  
}  
Default Method in Interface

interface Drawable{  
void draw();  
default void msg()
{
System.out.println("default method");
}  
}  
class Rectangle implements Drawable{  
public void draw()
{
System.out.println("drawing rectangle");
}  
}  
class TestInterfaceDefault{  
public static void main(String args[]){  
Drawable d=new Rectangle();  
d.draw();  
d.msg();  
}
}  
Static Method in Interface
interface Drawable{  
void draw();  
static int cube(int x)
{
return x*x*x;
}  
}  
class Rectangle implements Drawable{  
public void draw()
{
System.out.println("drawing rectangle");
}  
}  
  
class TestInterfaceStatic{  
public static void main(String args[]){  
Drawable d=new Rectangle();  
d.draw();  
System.out.println(Drawable.cube(3));  
}
}  
Summary:

• The class which implements the interface needs to provide functionality


for the methods declared in the interface
• All methods in an interface are implicitly public and abstract
• An interface cannot be instantiated
• An interface reference can point to objects of its implementing classes
• An interface can extend from one or many interfaces. A class can extend
only one class but implement any number of interfaces
Exception Handling :
An Exception can be anything which interrupts the
normal flow of the program. When an exception occurs program
processing gets terminated and doesn’t continue further.
Exception handling allows us to control the normal
flow of the program by using exception handling in program.
Syntax of try catch : try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
Types of exceptions
There are two types of exceptions
1)Checked exceptions
2)Unchecked exceptions
Checked exceptions :
A checked exception is an exception that is checked (notified) by the
compiler at compilation-time, these are also called as compile time exceptions.
These exceptions cannot simply be ignored, the programmer should take care of
(handle) these exceptions.
Examples of Checked Exceptions :-
ClassNotFoundException
IllegalAccessException
NoSuchFieldException
EOFException etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions as the compiler
do not check
whether the programmer has handled them or not but it’s the duty of the
programmer to handle these exceptions .
Runtime exceptions are ignored at the time of compilation.

Examples of Unchecked Exceptions:-


ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
NegativeArraySizeException etc.
statement 1;  
statement 2;  
statement 3;  
statement 4;  
statement 5;//exception occurs  
statement 6;  
statement 7;  
statement 8;  
statement 9; 
statement 10; 
Suppose there are 10 statements in your program and there occurs an exception
at statement 5, the rest of the code will not be executed i.e. statement 6 to 10
will not be executed. If we perform exception handling, the rest of the statement
will be executed. That is why we use exception handling in Java.

 
Java exception handling is managed via five keywords: try, catch, throw, throws
, and finally

Keyword Description

try The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch or finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded by try block which means
we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the important code of the program. It is executed whether
an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies
that there may occur an exception in the method. It is always used with method signature.
Syntax of Java try-catch
try{    
//code that may throw an exception    
}catch(Exception_class_Name ref){} 
   
Syntax of try-finally block
try{    
//code that may throw an exception    
}finally{} 
Problem without exception handling
 
public class TryCatchExample1 {
public static void main(String[] args) {
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TryCatchExample1.main(TryCatchExample1.java:5)
Exception handling program
public class JavaExceptionExample{  
  public static void main(String args[]){  
   try{  
      //code that may raise exception  
      int data=100/0;  
   }catch(ArithmeticException e){System.out.println(e);}  
   //rest code of the program   
   System.out.println("rest of the code...");  
  }  
}  

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...
An example of Try catch in Java Output:
Error: Don't divide a number by zero
class Example1 { I'm out of try-catch block in Java.
public static void main(String args[]) {
int num1, num2;
try
{ // Try block to handle code that may cause exception
num1 = 0;
num2 = 62 / num1;
System.out.println("Try block message");
}
catch (ArithmeticException e) { // This block is to catch divide-by-zero error
System.out.println("Error: Don't divide a number by zero");
}
System.out.println("I'm out of try-catch block in Java.");
}}
Common Scenarios of Java Exceptions
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException  
 
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.
String s=null;  
System.out.println(s.length());//NullPointerException  
 
3) A scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];  
a[10]=50; //ArrayIndexOutOfBoundsException  
Multithreading
What is Thread in java ?
A thread is an independent path of execution within a program. Many
threads can run concurrently within a program.
A thread is a lightweight sub process, a smallest unit of processing. It is
a separate path of execution.
Multithreading
 Multithreading in java is a process of executing multiple threads
simultaneously.

 we use multithreading than multiprocessing because threads share a common


memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.

 Java Multithreading is mostly used in games, animation etc.


The life cycle of the thread in java is controlled by JVM. The java thread states are
as follows: 1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
New
The thread is in new state if we create an instance of Thread class but before
the invocation of start() method.
Runnable
The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.
Running
The thread is in running state if the thread scheduler has selected it.
Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to
run.
Terminated
A thread is in terminated or dead state when its run() method exits
How to Create Thread
There are two ways to create a thread:
1. By Extending Thread class
2. By Implementing Runnable interface.

Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method
named run().

public void run(): is used to perform action for a thread


1. By Extending Thread Class
 When the class extends a Tread class, it must override run() method
of the Thread class.
 Must supply a public void run() method
 Start a thread by invoking the start() method
 When a thread starts, it executes run()
 When run() returns, thread is finished/dead
Example Program:
class Multi extends Thread
{ Output :
Multi(int a) //Parameterized Constructor Result 100
{ Thread is running...
System.out.println("Result" +a);
}
public void run()
{
System.out.println("Thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi(100);
t1.start();
} }
2.By Implementing Runnable interface:
 A Thread can be created by extending Thread class also. But Java allows only
one class to extend, it won’t allow multiple inheritance. So it is always better to
create a thread by implementing Runnable interface. Java allows you to
implement multiple interfaces at a time.

 By implementing Runnable interface, you need to provide implementation for


run() method.

 To run this implementation class, create a Thread object, pass Runnable


implementation class object to its constructor. Call start() method on thread
class to start executing run() method.

 Implementing Runnable interface does not create a Thread object, it only


defines an entry point for threads in your object. It allows you to pass the
object to the Thread (Runnable implementation) constructor.
Example Program: Output:
class Multi3 implements Runnable Thread is running…

{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Synchronization:
The synchronization keyword in java creates a block of code referred to
as critical section.
(or)
Synchronization in java is the capability to control the access of multiple threads
to any shared resource.

Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
General Syntax :
Synchronized (object)
{
// statement to be synchronized
}
Types of Synchronization
There are two types of synchronization
1. Thread Synchronization
2. Process Synchronization
1. Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
2. Cooperation (Inter-thread communication in java)

1.Mutual Exclusive:
Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by three ways in java:
i. by synchronized method
ii. by synchronized block
iii. by static synchronization
1.Java synchronized method
class MyThread1 extends Thread
class Table {
{ Table t;
synchronized void printTable(int n) MyThread1(Table t)
{ //synchronized method {
for(int i=1;i<=5;i++) this.t=t;
{ }
System.out.println(n*i); public void run(){
try t.printTable(5);
{ }
Thread.sleep(400); }
}
catch(Exception e)
{
System.out.println(e); } } } }
Table obj = new Table(); //only one object
class MyThread2 extends Thread MyThread1 t1=new MyThread1(obj);
{ MyThread2 t2=new MyThread2(obj);
Table t; t1.start();
MyThread2(Table t) t2.start(); } }
{ Output:
this.t=t; 5
} 10
public void run(){ 15
t.printTable(100); 20
} } 25
class TestSynchronization2 100
{ public static void main(String args[]) 200
{ 300
400
500
2.Java synchronized Block:
 Synchronized block can be used to perform synchronization on any specific
resource of the method.
 Suppose you have 50 lines of code in your method, but you want to
synchronize only 5 lines, you can use synchronized block.
 If you put all the codes of the method in the synchronized block, it will work
same as the synchronized method.

Points to remember for Synchronized block


 Synchronized block is used to lock an object for any shared resource.
 Scope of synchronized block is smaller than the method.
Syntax
synchronized (object reference
expression)
{ //code block
}
Example : catch(Exception e)
class Table {
{ System.out.println(e);
void printTable(int n) }}}
{ } //end of the method
synchronized(this) }
{ //synchronized block class MyThread1 extends Thread
for(int i=1;i<=5;i++) {
{ Table t;
System.out.println(n*i); MyThread1(Table t)
try {
{ this.t=t;
Thread.sleep(400); }
}
public void run() class TestSynchronizedBlock1
{ {
t.printTable(5); public static void main(String args[])
} {
} Table obj = new Table(); //only one object
class MyThread2 extends Thread MyThread1 t1=new MyThread1(obj);
{ MyThread2 t2=new MyThread2(obj);
Table t; t1.start();
MyThread2(Table t) t2.start();
{ }}
this.t=t;
}
public void run()
{
t.printTable(100);
}
Output:
5
10
15
20
25
100
200
300
400
500

You might also like