Unit II - Packages, Interfaces and Threads
Unit II - Packages, Interfaces and Threads
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
There are three ways to access the package from outside the package.
//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
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
The relationship between classes and interfaces
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
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:
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.
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...");
}
}
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()
{
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.