You are on page 1of 30

Interfaces: Multiple Inheritance

class A extends B extends C { .. } Such type of definitions are not permitted in java

Interfaces
An interface is basically a kind of class with the difference that interfaces define only abstract methods and final fields. Interfaces do not specify any code to implement these methods and data fields contain only constants

Interfaces
It is the responsibility of the class that implements an interface to define the code for implementation of these methods inteface InterfaceName { variables declaration; methods declaration; }

Extending Interfaces
interface ItemConstants { int code=1001; String name=Fan; } Interface ItemMethods { void display( ); } Interface Item extends ItemConstants,ItemMethods { .. }

Interfaces
Subinterfaces are not allowed to define the methods declared in the superinterfaces. Why?

Class Implementing Interfaces


interface Area { final static float pi=3.14; float compute ( float x, float y); } Class Rectangle implements Area { public float compute(float x, float y) { return (x* y); } } Class InterfaceTest { public static void main(String args[]){ Rectangle rect=new Rectangle( ); Area area; area=rect; System.out.println(Area of rectangle = + area.compute(10,20)); } }

Implementing Multiple Inheritance


class Student { int rollNumber; void getNumber( int n) { rollNumber=n; } void putNumber( ) { System.out.println("Roll No :" + rollNumber); } } interface Sports { float sportWt=6.0F; void putWt( ); } class Results extends Student implements Sports { float total; public void putWt( ) { System.out.println("sport wt = "+ sportWt); } }

class Hybrid { public static void main(String args[]) { Results student1=new Results(); student1.getNumber(1234); student1.putWt(); } }

Packages
Packages are Javas way of grouping a variety of classes and/or interfaces together. The grouping is usually done according to functionality.

Benefits of Packages
1) The classes contained in the packages of other programs can be easily reused. 2) Classes can be unique 3) Way to hide classes thus preventing other programs or packages from accessing classes that are meant for internal use only 4) Provide a way for separating Design from Coding

Package Classification
Java API packages User defined packages
Java

lang

util

io

awt

net

applet

Using packages
Using import statements import java.util.Vector;

Creating Packages
package com.jiet; class Hello{ public static void main(String args[]) { System.out.println("Hello World"); } }

Compiling & Executing


Javac d . Hello.java Java com.jiet.Hello

Comparison (Java & C++)


Java has both kinds of comments like C++ does All method definitions are defined in the body of the class. Thus, as in C++ it would look like all the functions are inlined, but theyre not Class definitions are roughly the same form in Java as in C++, but theres no closing semicolon Theres no scope resolution operator :: in Java. Java uses the dot for everything, but can get away with it since you can define elements only within a class. Even the method definitions must always occur within a class, so there is no need for scope resolution there either.

Comparison (Java & C++)


All objects of non-primitive types can be created only via new Java does not support default arguments You cannot specify public, private, or protected inheritance in Java, as you can in C++ overridden methods in a derived class cannot reduce the access of the method in the base class. For example, if a method is public in the base class and you override it, your overridden method must also be public (the compiler checks for this) Java use dynamic binding for non-static methods and static binding for static methods automatically. No Virtual exists in Java

Threads
In java, Multitasking is achieved using threads Multithreading is programming paradigm where a program(process) is divided into two or more subprograms(processes) Java enables us to use multiple flows of control in developing programs. Each flows of control is a separate tiny program known as a thread that runs in parallel to others

Threads
The ability of a language to support multithreads is referred to as concurrency Threads in java are subprograms of a main program (main method), are known as lightweight threads or lightweight processes Any application that requires two or more things to be done at the same time, is probably a best one for use of threads

Creating Threads
Threads are implemented in the form of objects that contain a method called run( ). run( ) makes up the entire body of a thread
run( ) can be invoked by an object of the concerned thread How to create objects????

Two ways to create a thread


By creating a thread class: Define a class that extends Thread class and override the run( ) method with the code required by the thread By converting a class to a thread: Define a class that implements Runnable interface. The Runnable interface has only one method, run( )

Extending the Thread class


Declare the class as extending the Thread class Implement the run( ) method that is responsible for executing the sequence of code that the thread will execute Create a thread object and call the start( ) method to initiate the thread execution

Program
class A extends Thread { public void run( ) { for(int i=1;i<=5;i++) SOP(\tFrom Thread A: i=+i); SOP(Exit from A); } } class B extends Thread { public void run( ) { for(int j=1;j<=5;j++) SOP(\tFrom Thread B: j=+j; SOP(Exit from B); } } class ThreadTest { public static void main (String args[]) { new A( ).start( ); new B( ).start( ); } }

Stopping and Blocking a thread


aThread.stop( ); : causes thread to move into a dead state
sleep() // blocked for a specified time suspend( ) // blocked until further orders wait( ) // blocked until certain condition occurs Resume( ) is used in case of suspend( ) Notify( ) is used in case of wait( )

Life Cycle of a Thread


During the life time of a thread, it enters these states Newborn state Runnable state Running state Blocked state Dead satate

Note
Sleep( ) method throws exception so it is mandatory to catch it while using sleep( ) try{
sleep (1000); } catch(Exception e) { }

Thread Priority
Each thread is assigned a priority, which affects the order in which it is scheduled for running. The threads by default are of the same priority and that is 5(NORM_PRIORITY); Java permits us to set the priority of a thread using the setPriority( ) method Threadname.setPriority(intNumber); The intNumber is an integer value to which the threads priority is set. It can be between 1 to 10 However there are some constants available MIN_PRIORITY=1 NORM_PRIORITY=5 MAX_PRIORITY=10

Setting Priority- Example


Class ThreadPriority { public static void main(String args[]) { A threadA=new A( ); B threadB=new B( ); C threadC=new C( ); threadC.setPriority(Thread.MAX_PRIORITY); threadB.setPriority(threadA.getPriorty( )+1); } }

Synchronization

When two or more threads compete for the same resources, it leads to serious problems e.g. one thread may try to read a record from a file while another is still writing to the same file. Java enables us to overcome this problem using a technique known as synchronization The method that will read information from a file and the method that will update the same file may be declared as synchronized. Example: synchronized void update( ) { // code here is synchronized } When we declare a method synchronized, Java creates a monitor and hands it over to the thread that calls the method first time. As long as the thread holds the monitor, no other thread can enter the synchronized section of code.

Deadlock
Thread A synchronized method2( ) { synchronized method1 ( ) { .. } }
Thread B synchronized method1( ) { synchronized method2( ) { } }

Implementing the Runnable Interface


The runnable interface declares the run( ) method that is required for implementing threads. Declare the class as implementing the Runnable interafce Implement the run( ) method Create a thread by defining an object that is instantiated from this runnable class as the target of the thread Call the threads start( ) method to run the thread

Program
Class X implements Runnable //Step1 { public void run( ) //Step2 { .. } } Class RunnableTest { public static void main(String argas[]) { X runable=new X( ); Thread threadx=new Thread(runable); //Step3 threadX.start( ); //Step4 SOP(End of Thread); } }

You might also like