0% found this document useful (0 votes)
8 views16 pages

Java Unit-4 Final

Uploaded by

rajfelix1969
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
8 views16 pages

Java Unit-4 Final

Uploaded by

rajfelix1969
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 16

JAVA PROGRAMMING – UNIT IV

INTERFACES:
 Java does not support multiple inheritance. That is, classes in Java
cannot have more than one superclass.
 Java provides an interface to support the concept of multiple
inheritance. It can implement more than one interface.
 Interface is used for full abstraction. Abstraction is a process where you
show only “relevant” data and “hide” unnecessary details of an object from
the user.
 Interface looks like a class but it is not a class.
 We cannot create the object of an interface.
 An interface can have methods and variables just like the class but the
methods declared in interface are by default abstract.
 Methods in interfaces do not have body.

Syntax:
interface interfacename
{
variables declaration;
methods declaration;
}

For Example:
interface area
{
final static float pi=3.14f;
float compute(float r);
}

ACCESSING INTERFACE VARIABLES:


 Interfaces can be used to declare a set of constants that can be used in
different classes.
 The values can be used in any method, as part of any variable declaration,
or anywhere where we can use a final value.
 The variables declared in an interface are public, static and final by
default.
 Interface variables must be initialized at the time of declaration
otherwise compiler will throw an error.

variable declaration:
final static type varname = value;

For Example:
final static float pi=3.14f;

Page 1 of 16
JAVA PROGRAMMING – UNIT IV

EXTENDING INTERFACE:
 Interfaces can also be extended. That is, an interface can be subinterfaced
from other interfaces.
 It is achieved using “extends”.

Syntax:
interface name1
{
name1 interface
body of name1;
} extension
interface name2 extends name1
{ name2 interface
body of name2;
}

For Example:
interface areavar
{
final static float pi=3.14f;
}
interface areamethod extends areavar
{
float compute(float r);
}

IMPLEMENTING INTERFACES:
 Interfaces are used as “superclasses” whose properties are inherited by
classes.
 The class that implements interface must implement all the methods of
that interface.

Syntax:
interface interfacename
{
variable initialisation;
method declaration;
}
class classname implements interfacename
{
body of classname;
}

interfacename interface

implementation

classname class Page 2 of 16


JAVA PROGRAMMING – UNIT IV

For Example:
interface area
{
final static float pi=3.14f;
float compute(float r);
}
class circle implements area
{
public float compute(float r)
{
return (pi*r*r);
}
}
 You can implement more than one interface in your class.
 When a class implements more than one interface, they are separated by a
comma.
Syntax:
class classname implements interface1, interface2, ............
{
body of classname;
}
interface interface interface
name1 name2 ................... name N

implementation

classname class

 A class can extend another class while implementing interfaces.


Syntax:
class classname extends superclass
implements interface1, interface2, ............
{
body of classname;
}
interface interface interface
name1 name2 ................... name N

implementation

superclass class

extension

classname class
Page 3 of 16
JAVA PROGRAMMING – UNIT IV

Example Java Program to compute the area of the circle using Interface:

import java.io.*;
interface area
{
final static float pi=3.14f;
float compute(float r);
}
class circle implements area
{
public float compute(float r)
{
System.out.println("Radius = "+r);
return (pi*r*r);
}
}
class circlearea
{
public static void main(String args[ ])
{
circle c=new circle();
area a;
a=c;
System.out.println("Area of Circle = "+a.compute(5));
}
}

The output is as follows:


Radius = 5.0
Area of Circle = 78.5

MULTITHREADED PROGRAMMING:
 Executing several programs simultaneously is known as Multitasking.
 In system’s terminology, it is called multithreading.
 Multithreading is a conceptual programming paradigm where a program
is divided into two or more subprograms, which can be implemented
at the same time in parallel.
 A thread is similar to a program that has a single flow of control. It has a
beginning, a body and an end, and executes commands sequentially.
 A program that contains multiple flows of control is known as
multithreaded program.
 The ability of a language to support multithreads is referred to as
concurrency.
 Threads in Java are subprograms of a main program and share the same
memory space, they are known as lightweight threads.

Page 4 of 16
JAVA PROGRAMMING – UNIT IV
Main Thread

Main method Module

start start start

Switching Switching

Thread A Thread B Thread C

CREATING THREADS:
 Threads are implemented in the form of objects that contain a method
called run( ).
 The run( ) method is the heart and soul of any thread.
 The run( ) method should be invoked by an object.
 This can be achieved by creating the thread and initiating it with the
help of another thread method called start( ).
 A new thread can be created in two ways:
 By creating a thread class
Define a class that extends Thread class and override its run( )
method.
 By converting a class to a thread
Define a class that implements runnable interface.

EXTENDING THE THREAD CLASS:


The class runnable as a thread by extending the class java.lang.Thread.
It includes,
1. Declare the class as extending the Thread class.
2. Implement the run( ) method is responsible for executing the thread.
3. Create a thread object and call start( ) method to initiate the thread
execution.

1. Declaring the Class:


The Thread class can be extended as follows:
class mythread extends Thread
{
................
................
}
2. Implementing the run( ) Method:
 The run( ) method has been inherited by the class mythread.
 It overrides in order to the thread’s behaviour can be
implemented.

Page 5 of 16
JAVA PROGRAMMING – UNIT IV

public void run( )


{
..................
}
3. Starting New Thread:
 To create and run an instance of our thread class,
mythread a = new mythread( ); //creates the object
a.start( ); // invokes run( ) method
 When we create the object, the thread is in a new born state.
 The start( ) method causing the thread to move into the runnable state.
For Example,
import java.io.*;
class first extends Thread
{
public void run( )
{
for (int i=1; i<=5; i++)
{
System.out.println("From Thread First : i = "+i);
}
System.out.println("Exit from First");
}
}
class second extends Thread
{
public void run( )
{
for (int j=1; j<=5; j++)
{
System.out.println("From Thread Second : j = "+j);
}
System.out.println("Exit from Second");
}
}
class third extends Thread
{
public void run( )
{
for (int k=1; k<=5; k++)
{
System.out.println("From Thread Third : k = "+k);
}
System.out.println("Exit from Third");
}
}

Page 6 of 16
JAVA PROGRAMMING – UNIT IV

class multithreadtest
{
public static void main(String args[ ])
{
first f=new first( );
second s=new second( );
third t=new third( );
f.start( );
s.start( );
t.start( );
}
}

OUTPUT:

From Thread First : i = 1


From Thread Third : k = 1
From Thread Second : j = 1
From Thread First : i = 2
From Thread Third : k = 2
From Thread Second : j = 2
From Thread First : i = 3
From Thread Third : k = 3
From Thread Second : j = 3
From Thread First : i = 4
From Thread Third : k = 4
From Thread Second : j = 4
From Thread First : i = 5
From Thread Third : k = 5
From Thread Second : j = 5
Exit from First
Exit from Third
Exit from Second

STOPPING A THREAD:
 Whenever we want to stop a thread by using stop( ) method.
a.stop( );
 It causes the thread to move to the dead state.
 It is used when the premature death of a thread is desired.

BLOCKING A THREAD:
 A thread can also be temporarily suspended or blocked from entering
into the runnable state by using either of the following methods:

Page 7 of 16
JAVA PROGRAMMING – UNIT IV

 sleep( ) //blocked for a specified time.


 suspend( ) //blocked until further orders.
 wait( ) //blocked until certain condition occurs.
 resume( ) //invoked in the case of suspend( ).
 notify( ) //called in the case of wait( ).

LIFE CYCLE OF A THREAD:


During the life time of a thread, there are many states it can enter.
They include,
1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State

New
Thread Newborn

start stop

Active Running Runnablee stop Killed


Thread Dead Thread
yield

suspend
resume stop
sleep
notify
wait

Idle Thread
(Not Runnable) Blocked

State Transition Diagram of a Thread

Page 8 of 16
JAVA PROGRAMMING – UNIT IV

1. Newborn State:
When we create a thread object, the thread is in newborn state.
In this state,
 Schedule it for running using start( ) method. Or
 Kill it using stop( ) method.
If scheduled, it moves to the runnable state.

Newborn

start stop

Runnable State Dead State

2. Runnable State:
 The runnable state means that the thread is ready for execution
and is waiting for the availability of the processor.
 All threads have equal priority.
 They are given time slots for execution in round robin fashion,
i.e., first-come, first-serve manner.
 This process of assigning time to threads is known as time-slicing.
 The yield( ) method is used to relinquish control to another thread
of equal priority before its turn comes.
yield

.................. ..................

Running Thread Runnable Threads

3. Running State:
 suspend( ) method:
 suspend( ) method is useful when we want to suspend a thread for
some time due to certain reason, but do not want to kill it.
 A suspended thread can be revived by using the resume( ) method.

Page 9 of 16
JAVA PROGRAMMING – UNIT IV
suspend

resume

Running Runnable Suspended

 sleep( ) method:
 sleep( ) method put a thread to sleep for a specified time period.
 Where time is in milliseconds.
 The thread re-enters the runnable state as soon as this time period
is elapsed.
sleep(t)

after t

Running Runnable Sleeping

 wait( ) method:
 wait( ) method is used to wait until some event occurs.
 The thread can be scheduled to run again using the notify( )
method.
wait

notify

Running Runnable Waiting

4. Blocked State:
 A thread is said to be blocked when it is prevented from entering
into the runnable state and subsequently the running state.
 A blocked thread is considered “not runnable” but not dead and
fully qualified to run again.

5. Dead State:
 Every thread has a life cycle.
 A running thread ends its life when it has completed executing its
run( ) method which is known as natural death.
 We can kill it by sending the stop message to it at any state which
is called as premature death.

Page 10 of 16
JAVA PROGRAMMING – UNIT IV

For Example,

import java.io.*;
class first extends Thread
{
public void run( )
{
for (int i=1; i<=5; i++)
{
if (i==1)
yield( );
System.out.println("From Thread First : i = "+i);
}
System.out.println("Exit from First");
}
}
class second extends Thread
{
public void run( )
{
for (int j=1; j<=5; j++)
{
System.out.println("From Thread Second : j = "+j);
if (j==3)
stop( );
}
System.out.println("Exit from Second");
}
}
class third extends Thread
{
public void run( )
{
for (int k=1; k<=5; k++)
{
System.out.println("From Thread Third : k = "+k);
if (k==1)
try
{
sleep(1000);
}
catch (Exception e)
{
}
}

Page 11 of 16
JAVA PROGRAMMING – UNIT IV

System.out.println("Exit from Third");


}
}
class threadmethods
{
public static void main(String args[ ])
{
first f=new first( );
second s=new second( );
third t=new third( );
System.out.println("Start Thread First");
f.start( );
System.out.println("Start Thread Second");
s.start( );
System.out.println("Start Thread Third");
t.start( );
System.out.println("End of Main Thread")
}
}

OUTPUT:

Start Thread First


Start Thread Second
Start Thread Third
From Thread Second : j = 1
From Thread Second : j = 2
From Thread First : i = 1
From Thread First : i = 2
End of Main Thread
From Thread Third : k = 1
From Thread Second : j = 3
From Thread First : i = 3
From Thread First : i = 4
From Thread First : i = 5
Exit from First
From Thread Third : k = 2
From Thread Third : k = 3
From Thread Third : k = 4
From Thread Third : k = 5
Exit from Third

Page 12 of 16
JAVA PROGRAMMING – UNIT IV

PACKAGE:
 Package is similar to “class libraries”.
 Package is a way of grouping a variety of classes or interfaces together. (ie)
“containers” for classes.
Benefits:
 Class contained in the packages of other programs can be easily reused.
 In packages, classes can be unique compared with classes in other
packages.
 It has a way to hide classes.
 It provides a way for separating “design” from “coding”.
 Java packages are classified into two types:
1. Java API packages
2. User defined packages

JAVA API PACKAGES :


Java API package provides a large number of classes grouped into different
packages according to functionality.

Java

lang util io awt net applet

Frequently Used API Packages

Package name Contents


java.lang It includes strings, math functions, threads and exceptions.
java.util It uses for random numbers, hash tables, date, etc.
java.io Input and Output of data.
java.awt Support for implementing graphical user interface.
java.applet Creates and Implements applets.
Classes for networking. It is communicating with local
java.net
computers as well as with internet servers.

Page 13 of 16
JAVA PROGRAMMING – UNIT IV

USING SYSTEM PACKAGES:


Packages are organised in hierarchical structure.
java

awt

Color
Package containing awt package
Graphics

Font

Package containing classes

Classes containing methods


Image

Hierarchical representation of java.awt package

The java package contains the package awt, which in turn contains various
classes required for implementing graphical user interface.
There are two ways of accessing the classes stored in a package.
1. Fully qualified class name of the class that we want to use by the
“dot operator”.
ie., it allows the specified class in the specified package to be
imported. For example : import java.awt.colour;
2. To use many of the classes contained in the package.
ie., it imports every class contained in the specified package. For
example : import java.awt.*;

CREATING PACKAGES:
Creating our own package involves the following steps:
 Declare the package at the beginning of a file using the form.
package packagename; // package declaration
 Define the class that is to be put in the package and declare it public.
public class aa // class definition
{
------- (body of class)
}

Page 14 of 16
JAVA PROGRAMMING – UNIT IV

 Create a subdirectory under the directory where the main source files
are stored.
 Store the listing as the classname.java file in the subdirectory created.
 Compile the file. This creates .class file in the subdirectory.

ACCESSING A PACKAGE:
Java system package can be accessed either using a fully qualified class
name or using a shortcut approach through the “import” statement. The same
approach can be used to access the user-defined packages as well.
The import statement can be used to search a list of packages for a
particular class.
Syntax: import package1 [.package2] [.package3].classname;
Here, package1 is the name of the top level package, package2 is the name
of the package that is inside the package1 and so on. Finally explicit class name is
specified.
For example, import packagename. * ;
Here, Package name denotes a simple package or a hierarchy of packages.
The star (*) specifies that the compiler should search this entire package
hierarchy when it encounters a class name.
The major drawback of this approach is difficult to determine from which
package a particular member came.

ADDING A CLASS TO A PACKAGE:


 It is simple to add a class to an existing package.
package p1 ;
public class A
{
// body of A
}
 The package p1 contains one public class by name A. suppose we want to
add another class B to this package. This can be done as follows.
1. Define the class and make it public.
2. Place the package statement.
package p1;
Before the class definition as follows:
package p1;
public class B
{
// body of B
}
3. Store this as B.java file under the directory p1.
4. Compile B.java file. This will create a B.class file and place it in the
directory p1. Now the package p1 will contain both the classes A
and B.

Page 15 of 16
JAVA PROGRAMMING – UNIT IV

import p1. * ;
 Create a package with multiple public classes having the following steps:
1. Decide the name of the package.
2. Create a subdirectory with this name under the directory where
main source files are stored.
3. Create classes that are to be placed in the package in separate
source files and declare the package statement
package packagename;
at the top of each source file.
4. Switch to the subdirectory created earlier and compile each source
file. When completed, the package would contain .class files of all
the source files.

Page 16 of 16

You might also like