Java Unit-4 Final
Java Unit-4 Final
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);
}
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
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
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));
}
}
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
Switching Switching
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.
Page 5 of 16
JAVA PROGRAMMING – UNIT IV
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:
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
New
Thread Newborn
start stop
suspend
resume stop
sleep
notify
wait
Idle Thread
(Not Runnable) Blocked
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
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
.................. ..................
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
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
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
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
OUTPUT:
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
Page 13 of 16
JAVA PROGRAMMING – UNIT IV
awt
Color
Package containing awt package
Graphics
Font
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.
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