Presentation is loading. Please wait.

Presentation is loading. Please wait.

Four main OOP concepts abstraction creation of well-defined interface for an object, separate from its implementation e.g., Vector in Java e.g., key functionalities.

Similar presentations


Presentation on theme: "Four main OOP concepts abstraction creation of well-defined interface for an object, separate from its implementation e.g., Vector in Java e.g., key functionalities."— Presentation transcript:

1 Four main OOP concepts abstraction creation of well-defined interface for an object, separate from its implementation e.g., Vector in Java e.g., key functionalities (init, add, delete, count, print) which can be called independently of knowing how an object is implemented encapsulation keeping implementation details “private”, i.e., inside the implementation hierarchy an object is defined in terms of other objects Composition => larger objects out of smaller ones Inheritance => properties of smaller objects are “inherited” by larger objects polymorphism use code “transparently” for all types of same class of object i.e., “morph” one object into another object within same hierarchy

2 Advantages Can create new programs faster because we can reuse code Easier to create new data types Easier memory management Programs should be less bug-prone, as it uses a stricter syntax and type checking. `Data hiding', the usage of data by one program part while other program parts cannot access the data Will whiten your teeth

3 Disadvantages disadvantages of C++ over Java: Java protects you from making mistakes that C/C++ don’t, as you’ve C++ has many concepts and possibilities so it has a steep learning curve extensive use of operator overloading, function overloading and virtual functions can very quickly make C++ programs very complicated shortcuts offered in C++ can often make it completely unreadable, just like in C

4 Sample Hello.cpp #include using namespace std; main() { cout << "hello world\n"; cout << "hello" << " world" << endl; }

5 Data types simple native data types: bool, int, double, char, wchar_t bool is like boolean in Java wchar_t is “wide char” for representing data from character sets with more than 255 characters modifiers: short, long, signed, unsigned, e.g., short int floating point types: float, double, long double enum and typedef just like C

6 Operators same as C, with some additions if you recognize it from C, then it’s pretty safe to assume it is doing the same thing in C++ Operator overloading…

7 Type conversions All integer math is done using int datatypes, so all types (bool, char, short, enum) are promoted to int before any arithmetic operations are performed on them Mixed expressions of integer / floating types promote the lower type to the higher type according to the following hierarchy: int < unsigned < long < unsigned long < float < double < long double

8 Branching and Looping if, if/else just like C and Java while and for and do/while just like C and Java break and continue just like C and Java switch just like C and Java goto just like C (but don’t use it!!!)

9 Program structure just like in C program is a collection of functions and declarations language is block-structured declarations are made at the beginning of a block; allocated on entry to the block and freed when exitingthe block parameters are call-by-value unless otherwise specified

10 Arrays similar to C dynamic memory allocation handled using new and delete instead of malloc (and family) and free examples: int a[5]; char b[3] = { ’a’, ’b’, ’c’ }; double c[4][5]; int *p = new int(5); // space allocated and *p set to 5 int **q = new int[10]; // space allocated and q = &q[0] int *r = new int; // space allocated but not initialized

11 Defining c++ functions a function’s “signature” is its name plus number and type of arguments you can have multiple functions with same name, as long as the signatures are different example: void foo( int a, char b ); void foo( int a, int b ); void foo( int a ); void foo( double f ); main() { foo( 1,’x’ ); foo( 1,2 ); foo( 3 ); foo( 5.79 ); } OVERLOADING – when function name is used by more than one function

12 Pointers and References pointers are like C: int *p means “pointer to int” p = &i means p gets the address of object i. references are not like C!! they are basically aliases – alternative names – for the values stored at the indicated memory locations, e.g.: int n; int &nn = n; double a[10]; double &last = a[9]; The difference between them: int a = 5; // declare and define a int *p = &a; // p points to a int &refa = a; // alias (reference) for a *p = 7; // *p points to a, so a is assigned 7 refa = *p + 1; // a is assigned value of *p=7 plus 1

13 UNIT-II CLASSES AND OBJECTS

14 Classes and Objects Class:It is defined as blueprint or it is a collection of objects Objects:is an instance of a class

15 Declaring Class Almost like struct, the default privacy specification is private whereas with struct, the default privacy specification is public Example: class point { double x, y; // implicitly private public: void print(); void set( double u, double v ); }; classes can be nested (like java) static is like in Java, with some weird subtleties

16 Classes: function overloading and overriding overloading: when you use the same name for functions with different signatures functions in derived class supercede any functions in base class with the same name overriding: when you change the behavior of base-class function in a derived class DON’T OVERRIDE BASE-CLASS FUNCTIONS!! because compiler can invoke wrong version by mistake

17 Access specifiers public public members can be accessed from any function private members can only be accessed by class’s own members and by “friends” (see ahead) Protected Class members, derived, and friends. “access violations” when you don’t obey the rules... can be listed in any order can be repeated

18 Constructors and destructors constructors are called ctors in C++ take the same name as the class in which they are defined, like in Java destructors are called dtors in C++ take the same name as the class in which they are defined, preceded by a tilde (˜) sort of like finalize in Java ctors can be overloaded and can take arguments dtors can not default constructor has no arguments

19 More coding… class point { double x,y; public: point() { x=0;y=0; } // default point( double u ) {x =u; y=0; } // conversion point( double u, double v ) { x =u; y =v;}...}

20 Operator overloading Most operators can be overloaded in cpp Treated as functions But its important to understand how they really work

21 LIST OF OPERATORS + ~ - ! = * /= += << >> && ++ [] () new delete new[] -> >>=

22 Operators which cant be overloaded..* :: ?:

23 Types of overloading Unary overloading Binary overloading

24 Inheritance Objects are often defined in terms of hierarchical classes with a base class and one or more levels of classes that inherit from the classes that are above it in the hierarchy. For instance, graphics objects might be defined as follows:

25 Inheritance (continued) class A : base class access specifier B { member access specifier(s):... member data and member function(s);... } Valid access specifiers include public, private, and protected

26 Syntax for Inheritance class derivedClass : public baseClass { private : // Declarations of additional members, if needed. public: // Declarations of additional members, if needed. protected: // Declarations of additional members, if needed. } The derived class inherits from the base class: all public members, all protected members (see later), and the default constructor The additional members defined can have the same name (and type) as those of the base class (as when some base members are to be redefined)

27 Hierarchy

28 Example of Inherited Classes class Shape { protected: int width, height; public: void setDims (int a, int b){ width=a; height=b;} }; class Rectangle: public Shape { public: int area ( ) { return (width * height); } }; class Triangle: public Shape { public: int area ( ) { return (width * height/2); } }; class Square: public Rectangle { public: void setDims (int a){ width=a; height=a;} };

29 More on Inheritance Syntax class derivedClass : protected baseClass { …}; // Effect: all public members inherited from baseClass are // now protected members of derivedClass class derivedClass : private baseClass { …}; // Effect: all public and protected members inherited from // baseClass are now private members of derivedClass Multiple inheritance A class can inherit several classes at once: class derivedClass:public baseClass1,public baseClass2{ …}; Remark: Not recommended

30 Virtual Functions class Object3D { virtual void intersect(Ray *r, Hit *h); }; class Sphere : public Object3D { virtual void intersect(Ray *r, Hit *h); }; myObject->intersect(ray, hit); If a superclass has virtual functions, the correct subclass version will automatically be selected Sphere *mySphere = new Sphere(); Object3D *myObject = mySphere; A superclass pointer can reference a subclass object Actually calls Sphere::intersect Superclass Subclass

31 Pure Virtual Functions class Object3D { virtual void intersect(Ray *r, Hit *h) = 0; }; A pure virtual function has a prototype, but no definition. Used when a default implementation does not make sense. A class with a pure virtual function is called a pure virtual class and cannot be instantiated. (However, its subclasses can).

32 Basic Terminology: Polymorphism Polymorphism means “having many forms”. It allows different objects to respond to the same message in different ways, the response specific to the type of the object. E.g. the message displayDetails() of the Person class should give different results when send to a Student object (e.g. the enrolment number).

33 UNIT-III IO STREAMS

34 Input/Output Not part of the language; implemented in library (like C and Pascal) The C I/O library stdio.h is available quite cryptic to use fprint, fprintf, etc. The C++ library iostream is better type-safe extensible very easy to use

35 Iostream Basics << is "put to" operator >> is "get from" operator Three standard streams: cout, cin, cerr std::cin >> x; std::cout << “Hello world!”; std::cerr << “Oops!”; std::cout << x;

36 C++ Input/Output Library The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream classes. The most basic stream classes are the standard input/output streams: istream cin built-in input stream variable; by default hooked to keyboard ostream cout built-in output stream variable; by default hooked to console header file: C++ also provides stream types for reading from and writing to files: ifstream inFile; // input file stream object ofstream outFile; // output file stream object header file:

37 Standard Stream Objects cin – istream class, “tied to” (connected to) the standard input device (keyboard) cout – ostream class, “tied to” standard output device cerr – ostream class, standard error output, unbuffered clog – ostream class, also to standard error, buffered

38 Unformatted I/O cout.write(buffer, SIZE) cin.read(buffer, SIZE) The memory contents pointed by buffer is read/write. In formatted I/O, contents are translated into printable ASCII sequence

39 Format States setiosflag(iso::S) Where S can be skipws, left, right, dec, oct, showpoint, uppercase, fixed etc.

40 Write in a File #include … ofstream fileobj(“f.dat”, ios::out); // create output file object fileobj << data; // output to file ofstream is derived class from ostream

41 Read in a File #include … ifstream fileobj(“f.dat”, ios::in); // create input file object fileobj >> data; // read from file ifstream is derived class of istream C.f. Fig. 14.7

42 Open and Close File Using scope rule { ofstream myfile(“dat.d”, ios::out); myfile << x; } Explicit open and close ofstream myfile; myfile.open(“dat.d”, ios::out); myfile << x; myfile.close();

43 Sequential v.s. Random Access of Files Normally, cin or cout or file stream is used sequentially Using the stream member functions seekp( ) and write( ), we can do random file access

44 Ways of handling errors in C++ Errors can be dealt with at place error occurs –easy to see if proper error checking implemented –harder to read application itself and see how code works Exception handling –makes clear, robust, fault-tolerant programs –C++ removes error handling code from "main line" of program Common failures –new not allocating memory –out of bounds array subscript –division by zero –invalid function parameters

45 Why exception handling? Exception handling - catch errors before they occur –deals with synchronous errors (i.e., divide by zero) –does not deal with asynchronous errors - disk I/O completions, mouse clicks - use interrupt processing –used when system can recover from error exception handler - recovery procedure –typically used when error dealt with in different place than where it occurred –useful when program cannot recover but must shut down cleanly Exception handling should not be used for program control –not optimized, can harm program performance

46 Exception handling Exception handling improves fault-tolerance –easier to write error-processing code –specify what type of exceptions are to be caught Most programs support only single threads –techniques in this chapter apply for multithreaded OS as well (Windows NT, OS/2, some UNIX) Exception handling another way to return control from a function or block of code

47 When Exception Handling Should Be Used Error handling should be used for –processing exceptional situations –processing exceptions for components that cannot handle them directly –processing exceptions for widely used components (libraries, classes, functions) that should not process their own exceptions –large projects that require uniform error processing

48 Other Error-Handling Techniques Use assert –if assertion false, the program terminates Ignore exceptions –use this "technique" on casual, personal programs - not commercial! Abort the program –appropriate for nonfatal errors give appearance that program functioned correctly –inappropriate for mission-critical programs, can cause resource leaks Set some error indicator –program may not check indicator at all points the error could occur

49 Other Error-Handling Techniques con’t Test for the error condition – issue an error message and call exit –pass error code to environment setjump and longjump –in –jump out of deeply nested function calls back to an error handler. –dangerous - unwinds the stack without calling destructors for automatic objects (more later) specific errors –some have dedicated capabilities for handling them –if new fails to allocate memory new_handler function executes to deal with problem

50 Exception Handling: try, throw, catch A function can throw an exception object if it detects an error –object typically a character string (error message) or class object –if exception handler exists, exception caught and handled –otherwise, program terminates Format –enclose code that may have an error in try block –follow with one or more catch blocks each catch block has an exception handler –if exception occurs and matches parameter in catch block, code in catch block executed –if no exception thrown, exception handlers skipped and control resumes after catch blocks –throw point - place where exception occurred control cannot return to throw point

51 1. Class definition 1.1 Function definition 1// Fig. 13.1: fig13_01.cpp 2// A simple exception handling example. 3// Checking for a divide-by-zero exception. 4#include 5 6using std::cout; 7using std::cin; 8using std::endl; 9 10// Class DivideByZeroException to be used in exception 11// handling for throwing an exception on a division by zero. 12class DivideByZeroException { 13public: 14 DivideByZeroException() 15 : message( "attempted to divide by zero" ) { } 16 const char *what() const { return message; } 17private: 18 const char *message; 19}; 20 21// Definition of function quotient. Demonstrates throwing 22// an exception when a divide-by-zero exception is encountered. 23double quotient( int numerator, int denominator ) 24{ 25 if ( denominator == 0 ) 26 throw DivideByZeroException(); 27 28 return static_cast ( numerator ) / denominator; 29} The function is defined to throw an exception object if denominator == 0

52 1. Class definition 1.1 Function definition 1// Fig. 13.1: fig13_01.cpp 2// A simple exception handling example. 3// Checking for a divide-by-zero exception. 4#include 5 6using std::cout; 7using std::cin; 8using std::endl; 9 10// Class DivideByZeroException to be used in exception 11// handling for throwing an exception on a division by zero. 12class DivideByZeroException { 13public: 14 DivideByZeroException() 15 : message( "attempted to divide by zero" ) { } 16 const char *what() const { return message; } 17private: 18 const char *message; 19}; 20 21// Definition of function quotient. Demonstrates throwing 22// an exception when a divide-by-zero exception is encountered. 23double quotient( int numerator, int denominator ) 24{ 25 if ( denominator == 0 ) 26 throw DivideByZeroException(); 27 28 return static_cast ( numerator ) / denominator; 29} The function is defined to throw an exception object if denominator == 0

53 1. Class definition 1.1 Function definition 1// Fig. 13.1: fig13_01.cpp 2// A simple exception handling example. 3// Checking for a divide-by-zero exception. 4#include 5 6using std::cout; 7using std::cin; 8using std::endl; 9 10// Class DivideByZeroException to be used in exception 11// handling for throwing an exception on a division by zero. 12class DivideByZeroException { 13public: 14 DivideByZeroException() 15 : message( "attempted to divide by zero" ) { } 16 const char *what() const { return message; } 17private: 18 const char *message; 19}; 20 21// Definition of function quotient. Demonstrates throwing 22// an exception when a divide-by-zero exception is encountered. 23double quotient( int numerator, int denominator ) 24{ 25 if ( denominator == 0 ) 26 throw DivideByZeroException(); 27 28 return static_cast ( numerator ) / denominator; 29} The function is defined to throw an exception object if denominator == 0

54 1.2 Initialize variables 2. Input data 2.1 try and catch blocks 2.2 Function call 3. Output result 30 31// Driver program 32int main() 33{ 34 int number1, number2; 35 double result; 36 37 cout << "Enter two integers (end-of-file to end): "; 38 39 while ( cin >> number1 >> number2 ) { 40 41 // the try block wraps the code that may throw an 42 // exception and the code that should not execute 43 // if an exception occurs 44 try { 45 result = quotient( number1, number2 ); 46 cout << "The quotient is: " << result << endl; 47 } 48 catch ( DivideByZeroException ex ) { // exception handler 49 cout << "Exception occurred: " << ex.what() << '\n'; 50 } 51 52 cout << "\nEnter two integers (end-of-file to end): "; 53 } 54 55 cout << endl; 56 return 0; // terminate normally 57} try block encloses code that may throw an exception, along with code that should not execute if an exception occurs. catch block follows try block, and contains exception-handling code.

55 UNIT-IV AN OVERVIEW OF JAVA

56 History of a Young Java 1992 Oak for a PDA on a SPARC (*7) 1995 Official release as Java – Internet 1997 picoJava – Sun’s Java processor 1998 RTSJ specification start as JSR-01 1999 split into J2SE and J2EE 2000 J2ME 2002 RTSJ final release 2002 first version of JOP ;-)

57 What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed for easy Web/Internet applications Widespread acceptance

58 Java Features (1) Simple –fixes some clumsy features of C++ –no pointers –automatic garbage collection –rich pre-defined class library http://java.sun.com/j2se/1.4.2/docs/api/ http://java.sun.com/j2se/1.4.2/docs/api/ Object oriented –focus on the data (objects) and methods manipulating the data –all functions are associated with objects –almost all datatypes are objects (files, strings, etc.) –potentially better code organization and reuse

59 Interpreted –java compiler generate byte-codes, not native machine code –the compiled byte-codes are platform-independent –java bytecodes are translated on the fly to machine readable instructions in runtime (Java Virtual Machine) Portable –same application runs on all platforms –the sizes of the primitive data types are always the same –the libraries define portable interfaces Java Features (2)

60 Java Features (3) Reliable –extensive compile-time and runtime error checking –no pointers but real arrays. Memory corruptions or unauthorized memory accesses are impossible –automatic garbage collection tracks objects usage over time Secure –usage in networked environments requires more security –memory allocation model is a major defense –access restrictions are forced (private, public)

61 Java Features (4) Multithreaded –multiple concurrent threads of executions can run simultaneously –utilizes a sophisticated set of synchronization primitives (based on monitors and condition variables paradigm) to achieve this Dynamic –java is designed to adapt to evolving environment –libraries can freely add new methods and instance variables without any effect on their clients –interfaces promote flexibility and reusability in code by specifying a set of methods an object can perform, but leaves open how these methods should be implemented –can check the class type in runtime

62 Java Disadvantages Slower than compiled language such as C –an experiment in 1999 showed that Java was 3 or 4 times slower than C or C++ title of the article: “Comparing Java vs. C/C++ Efficiency Issues to Interpersonal Issues” (Lutz Prechelt) –adequate for all but the most time-intensive programs

63 Getting Started: (1) (1) Create the source file: –open a text editor, type in the code which defines a class (HelloWorldApp) and then save it in a file (HelloWorldApp.java) –file and class name are case sensitive and must be matched exactly (except the.java part) Example Code: HelloWorldApp.java /** * The HelloWorldApp class implements an application * that displays "Hello World!" to the standard output */ public class HelloWorldApp { public static void main(String[] args) { // Display "Hello World!" System.out.println("Hello World!"); }  Java is CASE SENSITIVE!

64 Getting Started: (2) (2) Compile the program: – compile HelloWorldApp.java by using the following command: javac HelloWorldApp.java it generates a file named HelloWorldApp.class  ‘javac’ is not recognized as an internal or external command, operable program or hatch file. javac: Command not found if you see one of these errors, you have two choices: 1) specify the full path in which the javac program locates every time. For example: C:\j2sdk1.4.2_09\bin\javac HelloWorldApp.java 2) set the PATH environment variable

65 Getting Started: (3) (3) Run the program: –run the code through: java HelloWorldApp –Note that the command is java, not javac, and you refer to HelloWorldApp, not HelloWorldApp.java or HelloWorldApp.class  Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorldApp if you see this error, you may need to set the environment variable CLASSPATH.

66 Language basics (1) Data types –8 primitive types: boolean, byte, short, int, long, float, double, char –Class types, either provided by Java, or made by programmers String, Integer, Array, Frame, Object, Person, Animal, … –Array types Variables –dataType identifier [ = Expression]: –Example variable declarations and initializations: int x; x=5; boolean b = true; Frame win = new Frame(); String x = “how are you?”; int[] intArray; intArray = new int[2]; intArray[0] = 12; intArray[1] = 6; Person pArray = new Person[10];

67 Java system overview

68 Java Primitive Data Types boolean either true or false char 16-bit Unicode character (unsigned) byte 8-bit integer (signed) short 16-bit integer (signed) int 32-bit integer (signed) long 64-bit integer (signed) float 32-bit floating-point (IEEE 754-1985) double 64-bit floating-point (IEEE 754-1985)

69 JVM Data Types reference Pointer to an object or array int 32-bit integer (signed) long 64-bit integer (signed) float 32-bit floating-point (IEEE 754-1985) double 64-bit floating-point (IEEE 754-1985) No boolean, char, byte, and short types –Stack contains only 32-bit and 64-bit data –Conversion instructions

70 Language basics (2) Flow of control – if, if-else, if-else if – switch – for, while, do-while – break – continue

71 Conditional Statements The if – else statement if ( boolean condition ) { //statement sequence } else { //alternative statement sequence } Form of the if – else statement Expression that evaluates to true or false Block of statements that are executed if the condition is true Statements executed otherwise The else clause is optional, and may not be needed in every situation in which a segment of code is executed conditionally

72 Conditional Statements Relational operators The boolean condition in an if – else statement is often expressed as a test of a relationship between two variables. Is x equal to y? Is x greater than or equal to 0? Is x less than size? Is x not equal to 0? These tests are expressed in java in terms of the relational operators ==tests whether the expressions on the left and right are equivalent <=Is expression on left less than or equal to exp. on right? <Is expression on left less than expression on right? >Is expression on left greater than expression on right? >=Is expression on left greater than or equal to exp. on right? !=tests whether the expressions on the left and right are not equal (x == y) (x >= 0) (x < size) (x != 0)

73 Conditional Statements Relational operators Be sure to distinguish between the relational operator == and the assignment operator = x == y x = y; Tests if the contents of variable x are the same as the contents of variable y Assigns the value stored in variable y to variable x (overwriting what is in x and leaving y unchanged) Several of the relational operators use two characters for their symbol. There must NOT be a space between these two characters. x == yx != yx = y

74 Conditional Statements Example import java.util.Scanner;//needed for input stream classes public class ConditionalStatementExample { public static void main (String [ ] args) { //convert a possibly negative integer received from the keyboard to //its positive (absolute) value System.out.println(“Enter an integer”); Scanner console = new Scanner(System.in); BufferedReader br = new BufferedReader(isr); int theInteger = console.nextInt( ); if (theInteger < 0) theInteger = - theInteger; System.out.println(“The absolute value is: ” + theInteger); } If the integer is already positive, do nothing – else clause is not needed.

75 Conditional Statements Programming style public static void main(String [ ] args) { //list of statements indented 2 to 4 spaces int num1, num2, num3 = 5; num1 = 3 * num3 % 7; num2 = 5 * num3 % 11; //which number is larger if (num1 >= num2) { num1 += num3; System.out.println(“The larger pair is num1, num3”); } else { num2 += num3; System.out.println(“The larger pair is num2, num3”); } Main block Block of stmts. contained in if -- block Block of stmts. contained in else -- block 2 to 4 spaces

76 Conditional Statements Programming style Note that if there is only a single statement in the if or else block, curly brackets are not needed. If there is more than one statement in one of these blocks, the curly brackets are required. if (boolean condition) statement; else statement; if (boolean condition) { statement; } else { statement; } Curly brackets optional Curly brackets required

77 Conditional Statements Nested if statements Consider a function that assigns a letter grade to a numerical test score. (The test score is supplied as a parameter – writing functions will be explained fully later, right now we only wish to illustrate a nested if statement. public char gradeGiver(int testScore) { if (testScore >= 90) return ‘A’; else if (testScore >= 80) return ‘B’; else if (testScore >= 70) return ‘C’; else//testScore < 70 return ‘F’: } If the condition is satisfied, the program returns from this function call. Only scores less than 90 are evaluated further inside this function. By convention, each if and else– block is indented 2 to 4 spaces.

78 Conditional Statements Nested if statements The preceding form is somewhat difficult to follow, therefore the preferred way of writing nested if statements is to use an else if construction. public char gradeGiver (int testScore) { if (testScore >= 90) return ‘A’; else if (testScore >= 80) return ‘B’; else if (testScore >= 70) return ‘C’; else return ‘F’; }

79 Introduction Java is a true OO language and therefore the underlying structure of all Java programs is classes. Anything we wish to represent in Java must be encapsulated in a class that defines the “state” and “behaviour” of the basic program components known as objects. Classes create objects and objects use methods to communicate between them. They provide a convenient method for packaging a group of logically related data items and functions that work on them. A class essentially serves as a template for an object and behaves like a basic data type “int”. It is therefore important to understand how the fields and methods are defined in a class and how they are used to build a Java program that incorporates the basic OO concepts such as encapsulation, inheritance, and polymorphism.

80 Classes A class is a collection of fields (data) and methods (procedure or function) that operate on that data. Circle centre radius circumference() area()

81 Classes A class is a collection of fields (data) and methods (procedure or function) that operate on that data. The basic syntax for a class definition: Bare bone class – no fields, no methods public class Circle { // my circle class } class ClassName [extends SuperClassName] { [fields declaration] [methods declaration] }

82 Adding Fields: Class Circle with fields Add fields The fields (data) are also called the instance varaibles. public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle }

83 Adding Methods A class with only data fields has no life. Objects created by such a class cannot respond to any messages. Methods are declared inside the body of the class but immediately after the declaration of data fields. The general form of a method declaration is: type MethodName (parameter-list) { Method-body; }

84 Adding Methods to Class Circle public class Circle { public double x, y; // centre of the circle public double r; // radius of circle //Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { return 3.14 * r * r; } Method Body

85 Data Abstraction Declare the Circle class, have created a new data type – Data Abstraction Can define variables (objects) of that type: Circle aCircle; Circle bCircle;

86 Class of Circle cont. aCircle, bCircle simply refers to a Circle object, not an object itself. aCircle Points to nothing (Null Reference) bCircle Points to nothing (Null Reference) null

87 Creating objects of a class Objects are created dynamically using the new keyword. aCircle and bCircle refer to Circle objects bCircle = new Circle() ; aCircle = new Circle() ;

88 Creating objects of a class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; P aCircle Q bCircle Before Assignment P aCircle Q bCircle Before Assignment

89 Automatic garbage collection The object does not have a reference and cannot be used in future. The object becomes a candidate for automatic garbage collection. Java automatically collects garbage periodically and releases the memory used to be used in the future.

90 Accessing Object/Circle Data Similar to C syntax for accessing data defined in a structure. Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0 ObjectName.VariableName ObjectName.MethodName(parameter-list)

91 Executing Methods in Object/Circle Using Object Methods: Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area(); sent ‘message’ to aCircle

92 Using Circle Class // Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { public static void main(String args[]) { Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.x = 10; // assigning value to data field aCircle.y = 20; aCircle.r = 5; double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.r+" Area="+area); System.out.println("Radius="+aCircle.r+" Circumference ="+circumf); } [C:\jdk4.3\bin]%: java MyMain Radius=5.0 Area=78.5 Radius=5.0 Circumference =31.400000000000002

93 93 Inheritance Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class or superclass The derived class is called the child class or subclass. Creates an is-a relationship The subclass is a more specific version of the Original (Remember has-a is aggregation.) Book NovelDictionary MysteryHistory

94 Inheritance The child class inherits the methods and data defined for the parent class To tailor a derived class, the programmer can add new variables or methods, or can modify the inherited ones Software reuse is at the heart of inheritance By using existing software components to create new ones, we capitalize on all the effort that went into the design, implementation, and testing of the existing software

95 95 Deriving Subclasses In Java, we use the reserved word extends to establish an inheritance relationship class Dictionary extends Book { // class contents }

96 Dictionary webster = new Dictionary(); webster.message(); webster.defMessage(); public class Book { protected int pages = 1500; public String message() { System.out.println(“Number of pages: ” + pages); } public class Dictionary extends Book { private int definitions = 52500; public void defMessage() { System.out.println(“Number of definitions” + definitions); System.out.println(“Definitions per page: ” + (definitions/pages)); } Number of pages: 1500 Number of definitions: 52500 Definitions per page: 35

97 Some Inheritance Details An instance of a child class does not rely on an instance of a parent class –Hence we could create a Dictionary object without having to create a Book object first Inheritance is a one-way street –The Book class cannot use variables or methods declared explicitly in the Dictionary class

98 98 The protected Modifier Visibility modifiers determine which class members are inherited and which are not Variables and methods declared with public visibility are inherited; those with private visibility are not But public variables violate the principle of encapsulation There is a third visibility modifier that helps in inheritance situations: protected

99 99 The protected Modifier The protected modifier allows a member of a base class to be inherited into a child Protected visibility provides –more encapsulation than public visibility does –the best possible encapsulation that permits inheritance

100 100 The super Reference Constructors are not inherited, even though they have public visibility Yet we often want to use the parent's constructor to set up the "parent's part" of the object The super reference can be used to refer to the parent class, and often is used to invoke the parent's constructor

101 The super Reference A child’s constructor is responsible for calling the parent’s constructor The first line of a child’s constructor should use the super reference to call the parent’s constructor The super reference can also be used to reference other variables and methods defined in the parent’s class

102 public class Book { protected int pages; Book(int numPages) { pages = numPages; } public class Dictionary { private int definitions; Dictionary(int numPages, int numDefinitions) { super(numPages); definitions = numDefinitions; }

103 Multiple Inheritance Java supports single inheritance, meaning that a derived class can have only one parent class Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents Collisions, such as the same variable name in two parents, have to be resolved Java does not support multiple inheritance In most cases, the use of interfaces gives us aspects of multiple inheritance without the overhead.

104 104 Overriding Methods When a child class defines a method with the same name and signature as a method in the parent class, we say that the child’s version overrides the parent’s version in favor of its own. –Signature: method’s name along with number, type, and order of its parameters The new method must have the same signature as the parent's method, but can have a different body The type of the object executing the method determines which version of the method is invoked

105 Overriding A parent method can be invoked explicitly using the super reference If a method is declared with the final modifier, it cannot be overridden The concept of overriding can be applied to data and is called shadowing variables Shadowing variables should be avoided because it tends to cause unnecessarily confusing code

106 public class Book { protected int pages; Book(int numPages) { pages = numPages; } public void message() { System.out.println(“Number of pages : ” + pages); } public class Dictionary { protected int definitions; Dictionary(int numPages, int numDefinitions) { super(numPages); definitions = numDefinitions; } public void message() { System.out.println(“Number of definitions” + definitions); System.out.println(“Definitions per page: ” + (definitions/pages)); super.message(); }

107 107 Overloading vs. Overriding data Overriding lets you define Don't confuse the concepts of overloading and overriding Overloading deals with multiple methods with the same name in the same class, but with different signatures Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Overloading lets you define a similar operation in different ways for different a similar operation in different ways for different object types

108 108 Class Hierarchies A child class of one parent can be the parent of another child, forming a class hierarchy Book NovelDictionary MysteryRomance

109 109 Class Hierarchies Two children of the same parent are called siblings –However they are not related by inheritance because one is not used to derive another. Common features should be put as high in the hierarchy as is reasonable An inherited member is passed continually down the line Therefore, a child class inherits from all its ancestor classes There is no single class hierarchy that is appropriate for all situations

110 110 The Object Class A class called Object is defined in the java.lang package of the Java standard class library All classes are derived from the Object class If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class Therefore, the Object class is the ultimate root of all class hierarchies

111 The Object Class The Object class contains a few useful methods, which are inherited by all classes For example, the toString method is defined in the Object class Every time we have defined toString, we have actually been overriding an existing definition The toString method in the Object class is defined to return a string that contains the name of the object’s class together along with some other information –All objects are guaranteed to have a toString method via inheritance, thus the println method can call toString for any object that is passed to it

112 The Object Class The equals method of the Object class returns true if two references are aliases We can override equals in any class to define equality in some more appropriate way The String class (as we've seen) defines the equals method to return true if two String objects contain the same characters Therefore the String class has overridden the equals method inherited from Object in favor of its own version

113 Packages Package A collection of related classes and/or interfaces Examples: The Java API java.lang Essential classes for the Java language java.text Facilities for formatting text output java.util Special utilities (e.g. Scanner) java.net Network communication Packages can be divided into subpackages java.awt Classes for GUIs and graphics java.awt.font Classes and interface for fonts java.awt.geom Classes for 2-dimensional objects

114 User-Defined Packages Packages enable a programmer organize the code into smaller logically related units A large program may consists of hundreds of classes (800 in one current project with NASA) Every class is part of some package If you do not specify a package a class becomes part of the default packageAccess Classes defined within the same package can access one another more easily (no need for imports, fully qualified names) Some classes, object fields only accessible to classes in samepackage

115 Defining Packages To define: add package statement to specify package containing the classes of a file package mypackage; … public class myClass { … } // myClass is part of mypackage Must be first non-comment statement in file _ Packages organized into subpackages using the notation foo.subpackage: package mypackage.mysubpackage; … public class myClass2 { … } // myClass2 is part of // mysubpackage, which is // within mypackage _ Packages in Eclipse _ Select File®New®Package _ Enter the full name of the package

116 Class Access and Packages class access within a package Classes within a package can refer to each other without full qualification If a class, or member within a class, is not declared public, it can only be accessed by other classes within the package Class access across packages A public class can be accessed from other packages Its name is fully qualified or it must be is imported to achieve this The public classes of a package can be seen as the interface of the package with the outside world Importing a package does not automatically import subpackages E.g. import java.awt.* does not import java.awt.font

117 Example Files: Driver.java Driver Files: Circle.java Rectangle.java OtherShape.java Files: PublicClass1.java PublicClass2.java Circle Rectangle OtherShape PublicClass1 NonPublicClass1 PublicClass2 graphics graphics.shapes graphics.otherstuff Packages: Files: Classes:

118 Exception Error occurred in execution time Abnormal termination of program Wrong execution result Provide an exception handling mechanism in language system –Improve the reliability of application program –Allow simple program code for exeception check and handling into source

119 Exception Definition Treat exception as an object All exceptions are instances of a class extended from Throwable class or its subclass. Generally, a programmer makes new exception class to extend the Exception class which is subclass of Throwable class.

120 Exception Definition class UserErr extends Exception { } class UserClass { UserErr x = new UserErr(); //... if (val < 1) throw x; } class UserErr extends Exception { } class UserClass { UserErr x = new UserErr(); //... if (val < 1) throw x; }

121 Exception Definition We can pass the object which contains a message for the exception in string form class UserErr extends Exception { UserErr(String s) super(s); // constructor } class UserClass { //... if (val < 1) throw new UserErr("user exception throw message"); } class UserErr extends Exception { UserErr(String s) super(s); // constructor } class UserClass { //... if (val < 1) throw new UserErr("user exception throw message"); }

122 Hierarchical Structure of Throwable Class Object Throwable Error Exception RuntimeException...

123 Definition of Exception Error Class –Critical error which is not acceptable in normal application program Exception Class –Possible exception in normal application program execution –Possible to handle by programmer

124 System-Defined Exception Raised implicitly by system because of illegal execution of program When cannot continue program execution any more Created by Java System automatically Exception extended from Error class and RuntimeException class

125 System-Defined Exception IndexOutOfBoundsException : –When beyond the bound of index in the object which use index, such as array, string, and vector ArrayStoreException : –When assign object of incorrect type to element of array NegativeArraySizeException : –When using a negative size of array NullPointerException : –When refer to object as a null pointer SecurityException : –When violate security. Caused by security manager IllegalMonitorStateException : –When the thread which is not owner of monitor involves wait or notify method

126 Programmer-Defined Exception Exceptions raised by programmer Check by compiler whether the exception handler for exception occurred exists or not –If there is no handler, it is error Sub class of Exception class

127 Exception Occurrence Raised implicitly by system Raised explicitly by programmer –throw Statement throw ThrowableObject; Throwable class or its sub class Throwable class or its sub class

128 Exception Occurrence class ThrowStatement extends Exception { public static void exp(int ptr) { if (ptr == 0) throw new NullPointerException(); } public static void main(String[] args) { int i = 0; ThrowStatement.exp(i); } class ThrowStatement extends Exception { public static void exp(int ptr) { if (ptr == 0) throw new NullPointerException(); } public static void main(String[] args) { int i = 0; ThrowStatement.exp(i); } java.lang.NullPointerException at ThrowStatement.exp(ThrowStatement.java:4) at ThrowStatement.main(ThrowStatement.java:8) java.lang.NullPointerException at ThrowStatement.exp(ThrowStatement.java:4) at ThrowStatement.main(ThrowStatement.java:8)

129 Exception Occurrence throws Statement –When programmer-defined exception is raised, if there is no exception handler, need to describe it in the declaration part of method [modifiers] returntype methodName(params) throws e1,...,ek { }

130 Exception Handling try-catch-finally Statement –Check and Handle the Exception try { // … } catch (ExceptionType1 identifier) { // … } catch (ExceptionType2 identifier) { // … } finally { // … } try { // … } catch (ExceptionType1 identifier) { // … } catch (ExceptionType2 identifier) { // … } finally { // … }

131 Exception Handling Default Exception Handler –When system-defined exception occurred, if programmer does not deal with it, it would be processed by default exception handler –Simple function to output error message and exit Execution Order of Exception Handler –Finally clause is executed independent of exception and catch

132 Exception Propagation public class Propagate { void orange() { int m = 25, i = 0; i = m / i; } void apple() { orange(); } public static void main(String[] args) { Propagate p = new Propagate(); p.apple(); } public class Propagate { void orange() { int m = 25, i = 0; i = m / i; } void apple() { orange(); } public static void main(String[] args) { Propagate p = new Propagate(); p.apple(); } Output by Default Exception Handler Output by Default Exception Handler ArithmeticException Occurred java.lang.ArithmeticException: / by zero at Propagate.orange(Propagate.java:4) at Propagate.apple(Propagate.java:8) at Propagate.main(Propagate.java:11) java.lang.ArithmeticException: / by zero at Propagate.orange(Propagate.java:4) at Propagate.apple(Propagate.java:8) at Propagate.main(Propagate.java:11)

133 Exception Propagation Explicit Description for possibility of Exception Occurrence –System-Defined Exception Do not need to announce the possibility of exception occurrence –Programmer-Defined Exception When it is not managed in correspond method, the exception type should be informed. Use the throws clause

134 Exception Propagation class MyException extends Exception { } public class ClassA { // … public void methodA() throws MyException { // … if (someErrCondition()) throw new MyException(); // … } class MyException extends Exception { } public class ClassA { // … public void methodA() throws MyException { // … if (someErrCondition()) throw new MyException(); // … }

135 What are Threads? A piece of code that run in concurrent with other threads. Each thread is a statically ordered sequence of instructions. Threads are being extensively used express concurrency on both single and multiprocessors machines. Programming a task having multiple threads of control – Multithreading or Multithreaded Programming.

136 A single threaded program class ABC { …. public void main(..) { ….. } begin body end

137 A Multithreaded Program Main Thread Thread A Thread BThread C start Threads may switch or exchange data/results

138 Java Threads Java has built in thread support for Multithreading Synchronization Thread Scheduling Inter-Thread Communication: –currentThreadstartsetPriority –yieldrungetPriority –sleepstopsuspend –resume Java Garbage Collector is a low-priority thread

139 Threading Mechanisms... Create a class that extends the Thread class Create a class that implements the Runnable interface

140 1st method: Extending Thread class Threads are implemented as objects that contains a method called run() class MyThread extends Thread { public void run() { // thread body of execution } Create a thread: MyThread thr1 = new MyThread(); Start Execution of threads: thr1.start();

141 141 An example class MyThread extends Thread { // the thread public void run() { System.out.println(" this thread is running... "); } } // end class MyThread class ThreadEx1 { // a program that utilizes the thread public static void main(String [] args ) { MyThread t = new MyThread(); // due to extending the Thread class (above) // I can call start(), and this will call // run(). start() is a method in class Thread. t.start(); } // end main() } // end class ThreadEx1

142 2nd method: Threads by implementing Runnable interface class MyThread implements Runnable {..... public void run() { // thread body of execution } Creating Object: MyThread myObject = new MyThread(); Creating Thread Object: Thread thr1 = new Thread( myObject ); Start Execution: thr1.start();

143 143 An example class MyThread implements Runnable { public void run() { System.out.println(" this thread is running... "); } } // end class MyThread class ThreadEx2 { public static void main(String [] args ) { Thread t = new Thread(new MyThread()); // due to implementing the Runnable interface // I can call start(), and this will call run(). t.start(); } // end main() } // end class ThreadEx2

144 144 Life Cycle of Thread new runnable non-runnable dead wait() sleep() suspend() blocked notify() slept resume() unblocked start() stop()

145 Three threads example class A extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("\t From ThreadA: i= "+i); } System.out.println("Exit from A"); } class B extends Thread { public void run() { for(int j=1;j<=5;j++) { System.out.println("\t From ThreadB: j= "+j); } System.out.println("Exit from B"); }

146 class C extends Thread { public void run() { for(int k=1;k<=5;k++) { System.out.println("\t From ThreadC: k= "+k); } System.out.println("Exit from C"); } class ThreadTest { public static void main(String args[]) { new A().start(); new B().start(); new C().start(); } }

147 Run 1 [C:\jdk1.3\bin] threads [1:76] java ThreadTest From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 3 From ThreadA: i= 4 From ThreadA: i= 5 Exit from A From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5 Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5 Exit from B

148 Run2 [C:\jdk1.3\bin] threads [1:77] java ThreadTest From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 3 From ThreadA: i= 4 From ThreadA: i= 5 From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5 Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5 Exit from B Exit from A

149 Shared Resources If one thread tries to read the data and other thread tries to update the same date, it leads to inconsistent state. This can be prevented by synchronising access to data. In Java: “Synchronized” method: –syncronised void update() –{ … –}

150 150 the driver: 3 rd Threads sharing the same object class InternetBankingSystem { public static void main(String [] args ) { Account accountObject = new Account (); Thread t1 = new Thread(new MyThread(accountObject)); Thread t2 = new Thread(new YourThread(accountObject)); Thread t3 = new Thread(new HerThread(accountObject)); t1.start(); t2.start(); t3.start(); // DO some other operation } // end main() }

151 151 Program with 3 threads and shared object class MyThread implements Runnable { Account account; public MyThread ( Account s) { account = s;} public void run() { account.deposit(); } } // end class MyThread class YourThread implements Runnable { Account account; public YourThread ( Account s) { account = s; } public void run() { account.withdraw(); } } // end class YourThread class HerThread implements Runnable { Account account; public HerThread ( Account s) { account = s; } public void run() {account.enquire(); } } // end class HerThread accoun t

152 152 Monitor (shared object) example class Account { // the 'monitor' // DATA Members int balance; // if 'synchronized' is removed, the outcome is unpredictable public synchronized void deposit( ) { // METHOD BODY : balance += deposit_amount; } public synchronized void withdraw( ) { // METHOD BODY: balance -= deposit_amount; } public synchronized void enquire( ) { // METHOD BODY: display balance. }

153 Thread Priority In Java, each thread is assigned priority, which affects the order in which it is scheduled for running. The threads so far had same default priority (ORM_PRIORITY) and they are served using FCFS policy. –Java allows users to change priority: ThreadName.setPriority(intNumber) –MIN_PRIORITY = 1 –NORM_PRIORITY=5 –MAX_PRIORITY=10

154 Thread Priority Example class A extends Thread { public void run() { System.out.println("Thread A started"); for(int i=1;i<=4;i++) { System.out.println("\t From ThreadA: i= "+i); } System.out.println("Exit from A"); } class B extends Thread { public void run() { System.out.println("Thread B started"); for(int j=1;j<=4;j++) { System.out.println("\t From ThreadB: j= "+j); } System.out.println("Exit from B"); }

155 Thread Priority Example class C extends Thread { public void run() { System.out.println("Thread C started"); for(int k=1;k<=4;k++) { System.out.println("\t From ThreadC: k= "+k); } System.out.println("Exit from C"); } 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.getPriority()+1); threadA.setPriority(Thread.MIN_PRIORITY); System.out.println("Started Thread A"); threadA.start(); System.out.println("Started Thread B"); threadB.start(); System.out.println("Started Thread C"); threadC.start(); System.out.println("End of main thread"); }

156 Strings Java provides a class definition for a type called String Since the String class is part of the java.lang package, no special imports are required to use it (like a header file in C). Just like regular datatypes (and like C), variables of type String are declared as: String s1; String s2, s3; //etc. Note that String is uppercase. This is the Java convention for classnames.

157 Strings Initializing a String is painless s1 = “This is some java String”; Note that double quotes are required. Memory is allocated dynamically. Think of above method as shortcut for more standard way (assuming s1 has been declared): s1 = new String(“This is some java String”); new operator required to create memory for new String object.

158 String methods Given a String object we can then access any public String method or instance variable (field). Best to think of analogy with C. Given a variable of some struct type, we can access any of the struct’s members. If one of these members is a pointer to a function, we can essentially call a function using the struct. (x.doit(x,…)) In Java, this idea is taken quite a bit further, but the above analogy is a good start.

159 String Examples Best to see by way of example: String s = new String(“Hello”); Char c = s.charAt(3); System.out.println(c); Method charAt called on String object s taking single integer parameter. How might this look in a procedural language with structures? (homework)

160 Streams Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) –it acts as a buffer between the data source and destination Input stream: a stream that provides input to a program –System.in is an input stream Output stream: a stream that accepts output from a program –System.out is an output stream A stream connects a program to an I/O object –System.out connects a program to the screen –System.in connects a program to the keyboard

161 Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for data (sometimes both) An input stream may be associated with the keyboard An input stream or an output stream may be associated with a file Different streams have different characteristics: –A file has a definite length, and therefore an end –Keyboard input has no specific end

162 How to do I/O import java.io.*; Open the stream Use the stream (read, write, or both) Close the stream

163 Why Java I/O is hard Java I/O is very powerful, with an overwhelming number of options Any given kind of I/O is not particularly difficult The trick is to find your way through the maze of possibilities open use close

164 Opening a stream There is data external to your program that you want to get, or you want to put data somewhere outside your program When you open a stream, you are making a connection to that external place Once the connection is made, you forget about the external place and just use the stream open use close

165 Example of opening a stream A FileReader is a used to connect to a file that will be used for input: FileReader fileReader = new FileReader(fileName); The fileName specifies where the (external) file is to be found You never use fileName again; instead, you use fileReader open use close

166 Using a stream Some streams can be used only for input, others only for output, still others for both Using a stream means doing input from it or output to it But it’s not usually that simple--you need to manipulate the data in some way as it comes in or goes out open use close

167 Example of using a stream int ch; ch = fileReader.read( ); The fileReader.read() method reads one character and returns it as an integer, or -1 if there are no more characters to read The meaning of the integer depends on the file encoding (ASCII, Unicode, other) open use close

168 Manipulating the input data Reading characters as integers isn’t usually what you want to do A BufferedReader will convert integers to characters; it can also read whole lines The constructor for BufferedReader takes a FileReader parameter: BufferedReader bufferedReader = new BufferedReader(fileReader); open use close

169 Reading lines String s; s = bufferedReader.readLine( ); A BufferedReader will return null if there is nothing more to read open use close

170 Closing A stream is an expensive resource There is a limit on the number of streams that you can have open at one time You should not have more than one stream open on the same file You must close a stream before you can open it again Always close your streams! open use close

171 Text files Text (.txt ) files are the simplest kind of files –text files can be used by many different programs Formatted text files (such as.doc files) also contain binary formatting information Only programs that “know the secret code” can make sense formatted text files Compilers, in general, work only with text

172 My LineReader class class LineReader { BufferedReader bufferedReader; LineReader(String fileName) {...} String readLine( ) {...} void close( ) {...} }

173 Basics of the LineReader constructor Create a FileReader for the named file: FileReader fileReader = new FileReader(fileName); Use it as input to a BufferedReader : BufferedReader bufferedReader = new BufferedReader(fileReader); Use the BufferedReader ; but first, we need to catch possible Exception s

174 The full LineReader constructor LineReader(String fileName) { FileReader fileReader = null; try { fileReader = new FileReader(fileName); } catch (FileNotFoundException e) { System.err.println ("LineReader can't find input file: " + fileName); e.printStackTrace( ); } bufferedReader = new BufferedReader(fileReader); }

175 readLine String readLine( ) { try { return bufferedReader.readLine( ); } catch(IOException e) { e.printStackTrace( ); } return null; }

176 close void close() { try { bufferedReader.close( ); } catch(IOException e) { } }

177 How did I figure that out? I wanted to read lines from a file I found a readLine method in the BufferedReader class The constructor for BufferedReader takes a Reader as an argument An InputStreamReader is a kind of Reader A FileReader is a kind of InputStreamReader

178 The LineWriter class class LineWriter { PrintWriter printWriter; LineWriter(String fileName) {...} void writeLine(String line) {...} void close( ) {...} }

179 The constructor for LineWriter LineWriter(String fileName) { try { printWriter = new PrintWriter( new FileOutputStream(fileName), true); } catch(Exception e) { System.err.println("LineWriter can't " + "use output file: " + fileName); }

180 Flushing the buffer When you put information into a buffered output stream, it goes into a buffer The buffer may not be written out right away If your program crashes, you may not know how far it got before it crashed Flushing the buffer is forcing the information to be written out

181 PrintWriter Buffers are automatically flushed when the program ends normally Usually it is your responsibility to flush buffers if the program does not end normally PrintWriter can do the flushing for you public PrintWriter(OutputStream out, boolean autoFlush)

182 writeLine void writeLine(String line) { printWriter.println(line); }

183 close void close( ) { printWriter.flush( ); try { printWriter.close( ); } catch(Exception e) { } }

184 Serialization You can also read and write objects to files Object I/O goes by the awkward name of serialization Serialization in other languages can be very difficult, because objects may contain references to other objects Java makes serialization (almost) easy

185 Conditions for serializability If an object is to be serialized: –The class must be declared as public –The class must implement Serializable –The class must have a no-argument constructor –All fields of the class must be serializable: either primitive types or serializable objects

186 Implementing the Serializable interface To “implement” an interface means to define all the methods declared by that interface, but... The Serializable interface does not define any methods! –Question: What possible use is there for an interface that does not declare any methods? –Answer: Serializable is used as flag to tell Java it needs to do extra work with this class

187 Writing objects to a file ObjectOutputStream objectOut = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream(fileName))); objectOut.writeObject(serializableObject); objectOut.close( ); open use close

188 Reading objects from a file ObjectInputStream objectIn = new ObjectInputStream( new BufferedInputStream( new FileInputStream(fileName))); myObject = (itsType)objectIn.readObject( ); objectIn.close( ); open use close


Download ppt "Four main OOP concepts abstraction creation of well-defined interface for an object, separate from its implementation e.g., Vector in Java e.g., key functionalities."

Similar presentations


Ads by Google