Java Unit 3.pdf

Full Transcript

Java programming Unit - 3 Interface: multiple inheritance Introduction We discussed about classes and how the classes can be inherited by other classes. We learned about various inheritance types Java do not support multiple inheritance Class A extends B extends C { } But many real time a...

Java programming Unit - 3 Interface: multiple inheritance Introduction We discussed about classes and how the classes can be inherited by other classes. We learned about various inheritance types Java do not support multiple inheritance Class A extends B extends C { } But many real time applications require multiple inheritance to support that concept java provided a new approach known as interfaces Interface: multiple inheritance Defi ning Interface An interface is basically a class, like classes, interfaces contain methods and variables but with major difference The difference is that interface defi ne only abstract methods and fi nal fi elds. This means interface do not specify an code to implement the methods and data fi elds contain only constant. Therefore it is responsibility of the class that implements interface to defi ne the code implementation of these methods Interface: multiple inheritance Syntax of Defi ning Interface Within interface data items are declared as below: Within interface methods are declared as below: Interface: multiple inheritance Example of creating interface Note the code of the method is not included in the interface. The method declaration ends with semicolon. The class which implements the interface must provide the Interface: multiple inheritance Extending interface Like class, interfaces can also be extended. That is interface can be subinterfaced from other interfaces. The new subinterface will inherit all the members of superinterface in the manner similar to sub classes This a achieved using the keyword extends In the below example both variable code and name are not made fi nal as any data item declared within interface automatically becomes fi nal Interface: multiple inheritance We can also combine several interface into one interface Interface: multiple inheritance Implementing Interfaces Interface are used as super classes whose properties are inherited by classes. It is therefore necessary to create a class that inherits the given interface. This is done as follows Interface: multiple inheritance Implementing Interfaces More general form of interface implementation is as follows. Here the class can extend one class and implement multiple interfaces. Interface: multiple inheritance Implementing Interfaces When a class implements more than one interface they are separated by comma. The implementation of interfaces can take various forms as shown in the programs. Interface: multiple inheritance Diff erence between Class and Interface Class Interface The member of a class can be The member of interface are always constant The classor variables defi nition can contain the declared The methodsconstant and they in interface arevalues code It canfor be each of its methods. instanitiated That by declared are fi nal abstract It can notinbe nature usedthat is there is no to declare is It the method object can can access use various be abstract or er specifi code It canassociated object. It isuse only with onlythe for them. Later inheritance public access non abstract like public,private,protected the class purpose specfi er which implement the method should provide the code for it Example Interface Programs interface Area { fl oat compute(fl oat x, fl oat y); } class Rectangle implements Area { public fl oat compute(fl oat x, fl oat y) { return(x * y); } } class Triangle implements Area { public fl oat compute(fl oat x,fl oat y) { return(x * y/2); } } class InterfaceArea { public static void main(String args[]) { Rectangle rect = new Rectangle(); Triangle tri = new Triangle(); Area area; area = rect; Example Interface Programs accessing variables interface MyInterface { public static int num = 100; public void display(); } public class InterfaceExample implements MyInterface { public static int num = 10000; public void display() { System.out.println("This is the implementation of the display method"); } public void show() { System.out.println("This is the implementation of the show method"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); System.out.println("Value of num of the interface +MyInterface.num); System.out.println("Value of num of the class "+obj.num); } Example Interface Programs: //Interface declaration: by fi rst user interface Drawable{ void draw(); } //Implementation: by second user class Rectangle implements Drawable{ public void draw(){System.out.println("drawing rectangle");} } class Circle implements Drawable{ public void draw(){System.out.println("drawing circle");} } //Using interface: by third user class TestInterface1{ public static void main(String args[]){ Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable() Example Interface Programs: Multiple Inheritance interface Printable{ void print(); } interface Showable{ void show(); } class A7 implements Printable,Showable{ public void print(){System.out.println("Hello");} public void show(){System.out.println("Welcome");} public static void main(String args[]){ A7 obj = new A7(); obj.print(); obj.show(); } Example Interface Programs: Multiple Inheritance interface Exam { void Percent_cal(); } class Student { String name; int roll_no, Marks1, Marks2; Student(String n, int rn, int m1, int m2) { name = n; roll_no = rn; Marks1 = m1; Marks2 = m2; } void show() { System.out.println("Student Name : "+name); System.out.println("Roll no : "+roll_no); System.out.println("Marks1 : "+Marks1); System.out.println("Marks2 : "+Marks2); } } class Result extends Student implements Exam { fl oat per; Result(String n,int rn,int m1,int m2) { super(n,rn,m1,m2); } public void Percent_cal() { int tot = Marks1 + Marks2; per = (fl oat)tot / 2; } void display() { show(); System.out.println("Percentage = "+per); } } public class StudentDetails { public static void main (String[] args) { Package : Putting classes together One important feature of OOP is its ability to reuse the already created code One way of achieving reusability is inheritance If we have created a class in one project and if we need to use classes from other programs without physically copying them into the project. This can be done in java through package So another way of achieving reusability is use of package Package : Putting classes together Package in Java is a way of grouping a variety of classes and interfaces together The grouping is usually done using functionality The classes involved in performing certain functionality are grouped together So a package act like a container for classes If we put our classes into package we achieve the following benefi ts 1. The classes contained in package can be easily reused 2. In package classes can be unique compared with classes in other packages. That is two diff erent classes can have same name in two diff erent packages 3. Package provide a way to hide classes thus preventing other program from accessing classes which are meant for internal use only Package : Putting classes together Java Packages are classifi ed into two types Package : Putting classes together Java API Packages Java API provides large number of classes grouped into diff erent packages according to functionality These packages are available with Java API. These java API Packages contain diff erent classes which can be used in the project. Package : Putting classes together Package : Putting classes together Using system packages The packages are organized in a hierarchical structure. The package named java contains all the packages. The individual packages are in turn containing various classes and classes contains methods which can be called and reused. Package : Putting classes together Using system packages There are two ways in which the classes stored in package can be accessed 1. The fi rst approach is to use the fully qualifi ed class name which we want to reuse. For e.g java.awt.Color This approach is good if we want to reuse the Color class only once in program at one place. But if we want to use this class in number of places in the program then easy way I s import packagename.classname; For e.g import java.awt.Color; import java.awt.*; In the above example all the classes of awt are imported can be reused. Package : Putting classes together Naming Conventions The package can be named using the standard java naming rules By convention however we begin package name with lowercase For e.g java.awt.Point; Package : Putting classes together Creating Packages Till now we saw about system packages. But we can create our own package. This is done through using package Statement Package : Putting classes together Creating Packages Till now we saw about system packages. But we can create our own package. This is done through using package Statement Package : Putting classes together Steps for creating package 1. Declare the package at the beginning of a fi le using the form package < package name>; 2. Defi ne the class that is to be put in the package and declare it public 3. Create a subdirectory under the directory where the main source fi les are stored 4. Store the listing as class.java fi le in the subdirectory created 5. Compile the fi le. This creates.class fi le in the subdirectory Package : Putting classes together Steps for creating package 1. Declare the package at the beginning of a fi le using the form package < package name>; 2. Defi ne the class that is to be put in the package and declare it public 3. Create a subdirectory under the directory where the main source fi les are stored 4. Store the listing as class.java fi le in the subdirectory created 5. Compile the fi le. This creates.class fi le in the subdirectory Package : Putting classes together Accessing the Package We have discussed earlier that java system package can be accessed in two ways 1.By using full qualifi ed class name 2.By import statement by specifying package and class In case of user defi ned package also same approach can be used General form of import statement is as follows: import packagename1.packagename2.classname; import packagename1.*; Package : Putting classes together Accessing the Package We have discussed earlier that java system package can be accessed in two ways 1.By using full qualifi ed class name 2.By import statement by specifying package and class In case of user defi ned package also same approach can be used General form of import statement is as follows: import packagename1.packagename2.classname; import packagename1.*; Package : Putting classes together Example program for creating and using the package package mypack; public class p1 { public void msg() { System.out.println("Hello"); } } Save the above code as p1.java by crating the folder in bin with the name mypack Compile the code Package : Putting classes together Example program for creating and using the package import mypack.*; class p2 { public static void main(String args[]) { p1 ob = new p1(); ob.msg(); } } Multi threading Introduction Multithreading is conceptual programming paradigm where the program is divided into two or more subprograms (Processes) which can be implemented at same time in parallel. For example one program can display an animation on the screen while another can build the next animation to be displayed This is something dividing a task into subtask and assigning them to diff erent people for execution independently and simultaneously Introduction In most of our computers we have only a single processor and there for processor is doing on thing at a time However the processor witches between the processes so fast that it appears to human being that all of them are being done simultaneously Java program that we have seen and discussed so for contain single sequential fl ow of control. This is what happens when we execute a normal program. The program begin, runs through a sequence of execution and fi nally ends. At a given point of time there is only one statement for Introduction A thread is similar to program that has single fl ow of execution. It has a beginning, a body and an end and executes command sequentially. In fact all main program in our earlier example can be single thread. Every program has at least one thread A unique property of java is multithreading. That is java enables us to use multiple fl ow of control in developing program Each fl ow can be thought as separate tiny program Single Thread Multithread Introduction The threads created by main thread are like people living in the joint families and sharing certain resources by all. The sub programs of the main application program share the same memory space so that they are called light weight thread Multithreading is powerful programming tool that makes java distinctly different programming language. Multithreading is useful in number of ways It enables running multiple things at one time. They can divide a long program into thread execute them parallel The applications where two or more things to be done parallel requires the use of thread Creating Threads Creating thread in java is simple. Thread is implemented in the form of object which contain run() method The run() method is heart of thread public void run() { Statements for implementing thread Creating Thread The thread can be created in two ways 1.By creating a thread class Defi ne a class that extends Thread class and override the methods with the code required for the thread 2.By converting a class to thread Defi ne a class that implements Runnable interface has only one method run(), that is to be defi ned with the method code to be executed 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 Extending the Thread Class Declaring the class Implementing run() method The run method has been inherited by the class MyThread. We have to override it in order to implement the code to be executed by our thread. When we start the new thread, java calls run method How to start new Thread First create a new object of the class which extends Thread class Then call start() method to to move the thread into run() mode or move thread in running state Example of Thread Program Example of Thread Program Example of Thread Program Example of Thread Program Output Stopping Thread Whenever we want to stop a thread from running further, we may do so by calling stop() method Threadname.stop(); This causes the thread to move to dead state. The thread will also move to dead state once it reaches end of method. Blocking a Thread A thread can also be temporarily suspended or blocked from entering into runnable and run state by using the following thread methods 1. sleep() block thread for specifi c time 2. Suspend() block until further order 3. Wait() block until certain condition occurs When we block the thread it moves into non runnable state. But it can resume back and enter in runnable state when specifi c time passes in case of sleep() method, when resume() method is invoked in case of suspend and Thread Life Cycle During the life time of thread, there are many states the thread passes through. These states include 1.Newborn state 2.Runnable state 3.Running state 4.Blocked state 5.Dead state The thread is always in one of these fi ve states. It can move from one state to another in diff erent ways Thread Life Cycle Thread Life Cycle Newborn State When we create a thread object , the thread is new born and said to be in newborn state. The thread is not yet scheduled for running. We can either 1.Schedule it for running using start() method 2.Kill it using stop method Thread Life Cycle Runnable State The runnable state means that thread is ready for execution and is waiting for processor. That is the thread has joined the queue of threads that are waiting If all threads have equal priority they will get equal CPU time on round robin fashion After the time slot of CPU thread join the end of queue again. The time assigned to thread is called time slicing If one thread was to handover a control of CPU to another thread it can do so by using the yield() method Thread Life Cycle Running State Running means that processor has given its time to thread for its execution until it is gives back control on its own or it preempted by higher priority process it keep executing 1.It has been suspended using suspend method. The suspended thread can be restarted using resume() method. Running State 2. It has been made to sleep. We can put the thread to sleep for specifi ed time period method sleep(time) where time is in milliseconds. This means that the thread is out of queue during this time period. The thread re-enters the runnable state as soon as this time elapsed Running State 3. It has been told to wait until some event occur. This is done using wait() thread it an be scheduled to run again using notify() method Thread Life Cycle Blocked State A thread is said to be blocked when it is prevented from entering into the subsequently the runnable state and then to running state This happens when the thread is suspended, sleep or waiting. A blocked thread is considered “not runnable” therefore fully qualifi ed to run again Thread Life Cycle Dead State Every thread has a life cycle. A running thread ends it life when it has completed executing run() method. It is natural death. However we can kill by sending stop() message A thread can be killed as soon as it is born, or while it is running or even when it is in not runnable condition Example program on Thread Class class D extends Thread { public void run() { for(int i=0;i

Use Quizgecko on...
Browser
Browser