1 / 39

Classes & Objects Packages & Interfaces Multi-threading & Exception-Handling

Classes & Objects Packages & Interfaces Multi-threading & Exception-Handling. Classes. Java is a true object-oriented programming language and therefore everything in Java is a concept of the class . Therefore, class is at the core of Java.

brinda
Download Presentation

Classes & Objects Packages & Interfaces Multi-threading & Exception-Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Classes & Objects Packages & Interfaces Multi-threading & Exception-Handling

  2. Classes • Java is a true object-oriented programming language and therefore everything in Java is a concept of the class. Therefore, class is at the core of Java. • Classes create objects and use methods to communicate between them. Class definition A class is a user-defined data type with the template that serves to define its properties. A class defines a new data type which can be used to create objects of that type. Thus, class is a template for an object and object is the instance of the class. The code is contained within the methods.

  3. Adding variables to a class The data in a class is in the form of instance variables. We can declare the instance variables exactly the same way as we declare the local variables. For example: class Country { long population; float currencyRate; intnoOfStates; }

  4. Creating objects Objects are created using the ‘new’ operator. This ‘new’ operator creates an object of the specified class and returns the reference of that object. Let’s see the example for creating the object of the above class. Country japan; // declaration japan = new Country(); // instantiation

  5. Creating Objects contd.. Both statements can also be combined into one as shown below:  Country japan = new Country();  We can create any number of objects of the class ‘Country’ as, Country ksa = new Country(); Country china = new Country(); Country india = new Country(); After the objects are created, separate memory is allocated to them. The new operator dynamically (at run-time) allocates the memory for the object. It has the general form: class-var = new classname();

  6. Adding methods Methods are declared in the body of the class immediately after the declaration of instance variables. We can call method as a self contained block of statements that are used to perform a certain task. The general form of the declaration of the method is: data-type method-name (parameter-list) { Body of the method; }

  7. Ex program to find min and max using methods import java.util.Scanner; class Number { intmax(intx,int y) { if(x>y) return(x); else return(y); } intmin(intx,int y) { if(x<y) return(x); else return(y); } } class MaxMin { public static void main(String args[]) { int a, b; intmx, mn; Number n = new Number(); Scanner in = new Scanner(System.in); System.out.print("Enter first number : "); a = in.nextInt(); System.out.print("Enter second number :"); b = in.nextInt(); mx = n.max(a,b); System.out.print("\nMaximum : "+mx); mn = n.min(a,b); System.out.print("\nMinimum : "+mn);  } }

  8. Output Enter first number : 56 Enter second number : 84 Maximum : 84 Minimum : 56

  9. Constructors Let’s examine the constructor included for the class ‘Country’: class Country { long population; intnoOfStates; float currencyRate; Country(long x, int y) { population = x; noOfStates = y; } void display() { System.out.println(“Population:”+population); System.out.println(“No of states:”+noOfStates); } }

  10. The ‘this’ keyword The ‘this’ is used inside the method or constructor to refer its own object. ‘this’ keyword is used to differentiate between instance and local variables. Ex: Class Box{ //Class with instance variables Int height; Int depth; Int length;  Box(int height, int depth, int length) //Constructor with local variables { this.height = height; this.depth = depth; this.length = length; } }

  11. Creating the Inheritance A class can be derived from another class by following the syntax:  class subclassnameextendssuperclassname { //Body of the class; } The keyword ‘extends’ specifies that the properties of superclassname are extended to subclassname. After this the subclass will contain all the methods of super class and it will add the members of its own. Remember, we can not extend a sub class from more than one super class.

  12. Single Inheritance to find area of rectangle class Dimensions {int length;int breadth;}class Rectangle extends Dimensions {int a;void area(){a = length * breadth;} }class Area {public static void main(String args[]){Rectangle Rect = new Rectangle();Rect.length = 7;Rect.breadth = 16;Rect.area();System.out.println("The Area of rectangle of length "+Rect.length+" and breadth "+Rect.breadth+" is "+Rect.a);} }

  13. Output The Area of rectangle of length 7 and breadth 16 is 112

  14. The Visibility Controls Why: Many times it becomes necessary in some situations to restrict the access to certain variables and methods from outside the class. The visibility modifiers are also known as access modifiers. Like C++, Java also provides three different types of visibility modifiers i.e. public, private and protected.

  15. Public access

  16. Protected access

  17. Private access

  18. Arrays • An array is contiguous, or a group of related data items which have the same data type. • A position in the array is indicated by a non-negative integer value called as index. • The first element is always at index 0 and the last element at index n-1, where n is the value of array length. • For ex: intval[] = new int[5]; • Putting the values inside the array is ‘array initialization’. Ex: int num[] = { 45, 12, 56, 10, 20, 86, 19, 46, 30 };

  19. Strings • Strings are a sequence of characters. In Java, strings are objects. • The Java platform provides the String class to create and manipulate strings. • The most direct way to create a string is to write: String greeting = "Hello world!"; • Strings have many methods in Java, which can be used to modify the strings like length(), concat() etc.

  20. Packages • A package is called as the collection of classes and interfaces. • Java API (Application Program Interface) library provides a large number of classes grouped into different packages according to their functionality. Ex: import java.io.*; import java.awt.*; etc

  21. Fundamental Java packages The classes included in these packages are: java.lang – Language-supporting classes such as System, Thread, Exception etc. java.util – Utility classes such as Vector, Arrays, LinkedList, Stack etc. java.io – Input-output support classes such as BufferedReader, InputStream etc java.awt – Classes using GUI such as Window, Frame, Panel etc. java.applet – Classes for creating and implementing applets.

  22. Interfaces • An interface is an abstract type that is used to specify an interface that classes must implement. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations. • A class that implements an interface must implement all of the methods described in the interface. • One benefit of using interfaces is that they simulate multiple inheritance. • A Java class may implement, and an interface may extend, any number of interfaces.

  23. Interface Example For ex: interface College { int studs = 120; void play(); intcountUp(int x); } Interface Creation class myclassimplements College { public void play() { System.out.println(“Let’s play !!!”); } public intcountUp(int x) { x++; return(x); } } Interface Implementation

  24. Exception Handling • Exception is a condition that is caused by run-time error in the program. • As Java is strictly object oriented, an exception is also an object that describes an exceptional (that is, error) condition that has occurred in a piece of source code.

  25. Types of Exceptions • All exception types in Java are subclasses of the class java.lang.Throwable. Thus, Throwable is at the top of the exception class hierarchy. • Two of its subclasses are Exception and Error. • Exception class is used for exceptional conditions that user programs should catch. • There is an important subclass of Exception, called RuntimeException, which is automatically defined for the programs that we write. For ex: division by zero or I/O error etc. • Error class defines exceptions that are not expected to be caught under normal circumstances by the program. Ex: Stack overflow.

  26. Try-catch blocks The default exception handler provided by the Java run-time system is useful for debugging; we will usually want to handle an exception by ourselves. It provides two benefits. First, it allows us to fix the errors. Second, it prevents the program from automatically terminating. In order to take these two benefits Java has provided the mechanism of try-catch blocks. Its general form is as below: try { } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 }

  27. Exception-handling mechanism

  28. A simple try-catch block example class ArException{ public static void main(String args[]) { int x = 56; int y = 0; try { int z = x/y; //statement 1 System.out.println("Value: "+z); } catch(ArithmeticException e) { System.out.println("DIVISION BY ZERO"); } System.out.println("End of program..."); }}

  29. The finally block The finally is a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute, whether an exception is thrown or not. The try-catch-finallyconstruct can be created as: try {....... } catch(....) {....... } finally {....... }

  30. Example using finally block class FinallyClause{ public static void main(String args[]){ try{ intval = 0; //Statement1 intm = 100 / val; //statement2 int []x = new int[-5]; //statement3 System.out.println("No output"); } catch(ArithmeticException e){ System.out.println("Exception: "+e); } finally{ System.out.println("Program end"); System.out.println("Bye bye..."); } } }

  31. Multi-threading • One of the most important features of Java. • A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. • A thread is a light-weight process. • A thread is similar to a program that has single flow of control. It has beginning, the body and the end, and executes the statements sequentially. • With the careful use of multithreading, you can create very efficient programs.

  32. Multi-threading contd… • Example of a Java program containing four different threads, one main and three others:

  33. Multi-threading contd… • Threads exist in several states. A thread can be running. It can be readyto run as soon as it gets CPU time. A running thread can be suspended, which temporarily suspends its activity. A suspended thread can then be resumed, allowing it to pick up where it left off. A thread can be blocked when waiting for a resource. At any time, a thread can be terminated, which halts its execution immediately. Once terminated, a thread cannot be resumed.

  34. Life-cycle of a thread

  35. Main stages of a thread life-cycle There are many states in which a thread can enter during its life-time. These are: 1. Newborn state 2. Runnable state 3. Running state 4. Blocked state 5. Dead state

  36. Main stages of a thread life-cycle contd… Newborn state – Is when the thread object is created. We can either start this state to make it runnable using start( ) method or kill the thread using stop( ) method. Runnable state – Is when the thread is ready for execution and is waiting for availability of the processor. Running state – Is when the processor has given time to the thread for its execution. The thread runs until it transfers control to another thread.

  37. Main stages of a thread life-cycle contd… -> A thread transfers control in one of the following situations: • The thread has been suspended using suspend( ) method. This can be revived by using resume( ) method. This is useful when we want to suspend a thread for some time rather than killing it. • We can put a thread to sleep using sleep (time) method where ‘time’ is the time value given in milliseconds, means the thread is out of queue during this time period. • A thread can wait until some event occurs using wait( ) method. This thread can be scheduled to run again using notify( ) method. Blocked state – Is when a thread is prevented from entering into the runnablestate. A blocked thread is considered “not runnable”but not dead. Dead state - A running thread ends its life when it has completed its execution of run( ) method. It is a natural death. We can also kill a thread by sending the stop() method at any time (when running, blocked etc.).

  38. The Thread class and Runnable interface • Java’s multithreading system is built upon the Threadclass, its methods, and its companion interface called Runnable. • To create a new thread, program will either extend Thread or implement the Runnable interface.

  39. Example of a multi-threaded program class NewThreadimplements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(inti = 5; i > 0; i--) { System.out.println("Child Thread: " + i); // Let the thread sleep for a while. Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread try { for(inti = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } }

More Related