Top Banner
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
188

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.

Dec 21, 2015

Download

Documents

Griffin Goodwin
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 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.

Four main OOP concepts abstraction

• creation of well-defined interface for an object, separate from itsimplementation e.g., Vector in Java e.g., key functionalities (init, add, delete, count, print) which can becalled 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 largerobjects polymorphism

use code “transparently” for all types of same class of object i.e., “morph” one object into another object within same hierarchy

Page 2: 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.

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

Page 3: 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.

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

Page 4: 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.

Sample Hello.cpp

#include <iostream.h>

#include <stdio.h>

using namespace std;

main() {

cout << "hello world\n";

cout << "hello" << " world" << endl;

}

Page 5: 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.

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

Page 6: 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.

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…

Page 7: 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.

Type conversions

• All integer math is done using int datatypes, soall types (bool, char, short, enum) are promotedto int before any arithmetic operations areperformed on them• Mixed expressions of integer / floating typespromote the lower type to the higher typeaccording to the following hierarchy:int < unsigned < long < unsigned long< float < double < long double

Page 8: 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.

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!!!)

Page 9: 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.

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

Page 10: 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.

Arrays

• similar to C• dynamic memory allocation handled using new and

delete instead of malloc (and family) and freeexamples: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

Page 11: 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.

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

Page 12: 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.

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 indicatedmemory 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 aint *p = &a; // p points to aint &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

Page 13: 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.

UNIT-II

CLASSES AND OBJECTS

Page 14: 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.

Classes and Objects

• Class:It is defined as blueprint or it is a collection of objects

• Objects:is an instance of a class

Page 15: 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.

Declaring Class • Almost like struct, the default privacy specification is private

whereas• with struct, the default privacy specification is publicExample:class point {double x, y; // implicitly privatepublic:void print();void set( double u, double v );};• classes can be nested (like java)• static is like in Java, with some weird subtleties

Page 16: 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.

Classes: function overloading andoverriding

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

Page 17: 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.

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

Page 18: 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.

Constructors and destructors

constructors are called ctors in C++ take the same name as the class in which they

are defined, like in Javadestructors 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

Page 19: 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.

More coding…

class point{double x,y;public:point() { x=0;y=0; } // defaultpoint( double u ) {x =u; y=0; }// conversionpoint( double u, double v ){ x =u; y =v;}...}

Page 20: 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.

Operator overloading

• Most operators can be overloaded in cpp

• Treated as functions

• But its important to understand how they really work

Page 21: 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.

LIST OF OPERATORS

• +• ~• -• !• =• *• /=• +=• <<• >>

• &&• ++• []• ()• new• delete• new[]• ->• >>=

Page 22: 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.

Operators which cant beoverloaded

• .• .*• ::• ?:

Page 23: 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.

Types of overloading

• Unary overloading

• Binary overloading

Page 24: 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.

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:

Page 25: 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.

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

Page 26: 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.

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)

Page 27: 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.

Hierarchy

Page 28: 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.

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;}};

Page 29: 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.

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

Page 30: 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.

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

Sup

ercl

ass

Sub

clas

s

Page 31: 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.

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).

Page 32: 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.

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).

Page 33: 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.

UNIT-III

IO STREAMS

Page 34: 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.

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

Page 35: 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.

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;

Page 36: 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.

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: <iostream>• 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: <fstream>

Page 37: 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.

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

Page 38: 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.

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

Page 39: 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.

Format States

• setiosflag(iso::S)

• Where S can be skipws, left, right, dec, oct, showpoint, uppercase, fixed etc.

Page 40: 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.

Write in a File

#include <iostream>#include <fstream> …ofstream fileobj(“f.dat”, ios::out); // create output

file object

fileobj << data; // output to file

ofstream is derived class from ostream

Page 41: 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.

Read in a File

• #include <iostream>• #include <fstream>• …• 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

Page 42: 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.

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();

Page 43: 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.

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

Page 44: 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.

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

Page 45: 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.

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

Page 46: 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.

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

Page 47: 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.

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

Page 48: 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.

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

Page 49: 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.

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 <csetjmp>– 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

Page 50: 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.

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

Page 51: 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.

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 <iostream>

5

6 using std::cout;

7 using std::cin;

8 using std::endl;

9

10 // Class DivideByZeroException to be used in exception

11 // handling for throwing an exception on a division by zero.

12 class DivideByZeroException {

13 public:

14 DivideByZeroException()

15 : message( "attempted to divide by zero" ) { }

16 const char *what() const { return message; }

17 private:

18 const char *message;

19 };

20

21 // Definition of function quotient. Demonstrates throwing

22 // an exception when a divide-by-zero exception is encountered.

23 double quotient( int numerator, int denominator )

24 {

25 if ( denominator == 0 )

26 throw DivideByZeroException();

27

28 return static_cast< double > ( numerator ) / denominator;

29 }

The function is defined to throw an exception object if denominator == 0

Page 52: 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.

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 <iostream>

5

6 using std::cout;

7 using std::cin;

8 using std::endl;

9

10 // Class DivideByZeroException to be used in exception

11 // handling for throwing an exception on a division by zero.

12 class DivideByZeroException {

13 public:

14 DivideByZeroException()

15 : message( "attempted to divide by zero" ) { }

16 const char *what() const { return message; }

17 private:

18 const char *message;

19 };

20

21 // Definition of function quotient. Demonstrates throwing

22 // an exception when a divide-by-zero exception is encountered.

23 double quotient( int numerator, int denominator )

24 {

25 if ( denominator == 0 )

26 throw DivideByZeroException();

27

28 return static_cast< double > ( numerator ) / denominator;

29 }

The function is defined to throw an exception object if denominator == 0

Page 53: 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.

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 <iostream>

5

6 using std::cout;

7 using std::cin;

8 using std::endl;

9

10 // Class DivideByZeroException to be used in exception

11 // handling for throwing an exception on a division by zero.

12 class DivideByZeroException {

13 public:

14 DivideByZeroException()

15 : message( "attempted to divide by zero" ) { }

16 const char *what() const { return message; }

17 private:

18 const char *message;

19 };

20

21 // Definition of function quotient. Demonstrates throwing

22 // an exception when a divide-by-zero exception is encountered.

23 double quotient( int numerator, int denominator )

24 {

25 if ( denominator == 0 )

26 throw DivideByZeroException();

27

28 return static_cast< double > ( numerator ) / denominator;

29 }

The function is defined to throw an exception object if denominator == 0

Page 54: 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.

1.2 Initialize variables

2. Input data

2.1 try and catch blocks

2.2 Function call

3. Output result

30

31 // Driver program

32 int 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.

Page 55: 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.

UNIT-IV

AN OVERVIEW OF JAVA

Page 56: 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.

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 ;-)

Page 57: 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.

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

Page 58: 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.

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/

• 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

Page 59: 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.

• 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)

Page 60: 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.

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)

Page 61: 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.

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

Page 62: 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.

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

Page 63: 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.

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!

Page 64: 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.

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

Page 65: 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.

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.

Page 66: 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.

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];

Page 67: 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.

Java system overview

Page 68: 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.

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)

Page 69: 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.

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

Page 70: 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.

Language basics (2)

• Flow of control– if, if-else, if-else if– switch– for, while, do-while– break– continue

Page 71: 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.

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

Page 72: 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.

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)

Page 73: 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.

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 == y x != y x <= y x >= y

Page 74: 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.

Conditional StatementsExample

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.

Page 75: 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.

Conditional StatementsProgramming 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 -- block2 to 4 spaces

Page 76: 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.

Conditional StatementsProgramming 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;

statement;

}

else {

statement;

statement;

}Curly brackets optional

Curly brackets required

Page 77: 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.

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.

Page 78: 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.

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’;

}

Page 79: 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.

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.

Page 80: 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.

Classes

• A class is a collection of fields (data) and methods (procedure or function) that operate on that data.

Circle

centreradius

circumference()area()

Page 81: 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.

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]

}

Page 82: 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.

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

}

Page 83: 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.

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;}

Page 84: 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.

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

Page 85: 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.

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;

Page 86: 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.

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 null

Page 87: 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.

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() ;

Page 88: 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.

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

Page 89: 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.

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.

Page 90: 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.

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 radiusaCircle.y = 2.0aCircle.r = 1.0

ObjectName.VariableNameObjectName.MethodName(parameter-list)

Page 91: 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.

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

Page 92: 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.

Using Circle Class// Circle.java: Contains both Circle class and its user class//Add Circle class code hereclass 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.5Radius=5.0 Circumference =31.400000000000002

Page 93: 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.

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

Mystery History

Page 94: 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.

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

Page 95: 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.

95

Deriving Subclasses

• In Java, we use the reserved word extends to establish an inheritance relationship

class Dictionary extends Book {

// class contents}

Page 96: 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.

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

Page 97: 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.

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

Page 98: 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.

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

Page 99: 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.

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

Page 100: 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.

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

Page 101: 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.

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

Page 102: 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.

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; }}

Page 103: 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.

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.

Page 104: 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.

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

Page 105: 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.

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

Page 106: 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.

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(); }}

Page 107: 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.

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

Page 108: 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.

108

Class Hierarchies

• A child class of one parent can be the parent of another child, forming a class hierarchy Book

NovelDictionary

Mystery Romance

Page 109: 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.

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

Page 110: 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.

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

Page 111: 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.

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

Page 112: 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.

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

Page 113: 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.

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

Page 114: 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.

User-Defined Packages

Packages enable a programmer organize the code into smaller logically related unitsA large program may consists of hundreds of classes (800 inone current project with NASA) Every class is part of some packageIf you do not specify a package a class becomes part of the defaultpackageAccess 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

Page 115: 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.

Defining Packages

To define: add package statement to specify package containing the classes of a filepackage mypackage;…public class myClass { … } // myClass is part of mypackageMust be first non-comment statement in file_ Packages organized into subpackages using the notationfoo.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

Page 116: 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.

Class Access and Packagesclass 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 subpackagesE.g. import java.awt.* does not import java.awt.font

Page 117: 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.

Example

ExampleFiles:Driver.java DriverFiles:Circle.javaRectangle.javaOtherShape.javaFiles:PublicClass1.javaPublicClass2.javaCircleRectangleOtherShapePublicClass1NonPublicClass1PublicClass2graphicsgraphics.shapesgraphics.otherstuffPackages: Files: Classes:

Page 118: 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.

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

Page 119: 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.

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.

Page 120: 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.

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; }

Page 121: 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.

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"); }

Page 122: 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.

Hierarchical Structure of Throwable Class

ObjectObject

ThrowableThrowable

ErrorError ExceptionException

RuntimeExceptionRuntimeException

...

......

Page 123: 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.

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

Page 124: 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.

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

Page 125: 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.

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

Page 126: 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.

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

Page 127: 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.

Exception Occurrence

• Raised implicitly by system • Raised explicitly by programmer

– throw Statement

throw ThrowableObject; throw ThrowableObject;

Throwable class orits sub class

Throwable class orits sub class

Page 128: 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.

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)

Page 129: 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.

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 { } [modifiers] returntype methodName(params) throws e1, ... ,ek { }

Page 130: 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.

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 { // … }

Page 131: 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.

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

Page 132: 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.

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 ExceptionHandler

Output by Default ExceptionHandler

ArithmeticException OccurredArithmeticException Occurred

java.lang.ArithmeticException: / by zeroat Propagate.orange(Propagate.java:4)at Propagate.apple(Propagate.java:8)at Propagate.main(Propagate.java:11)

java.lang.ArithmeticException: / by zeroat Propagate.orange(Propagate.java:4)at Propagate.apple(Propagate.java:8)at Propagate.main(Propagate.java:11)

Page 133: 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.

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

Page 134: 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.

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(); // … } }

Page 135: 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.

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.

Page 136: 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.

A single threaded program

class ABC

{

….public void main(..)

{

..

}

}

begin

body

end

Page 137: 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.

A Multithreaded Program

Main Thread

Thread A Thread B Thread C

start startstart

Threads may switch or exchange data/results

Page 138: 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.

Java Threads

• Java has built in thread support for Multithreading

• Synchronization • Thread Scheduling• Inter-Thread Communication:

– currentThread start setPriority– yield run getPriority– sleep stop suspend– resume

• Java Garbage Collector is a low-priority thread

Page 139: 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.

Threading Mechanisms...

• Create a class that extends the Thread class• Create a class that implements the Runnable

interface

Page 140: 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.

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();

Page 141: 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.

141

An exampleclass 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

Page 142: 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.

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();

Page 143: 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.

143

An exampleclass 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

Page 144: 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.

144

Life Cycle of Thread

new

runnable non-runnable

dead

wait()sleep()suspend()blocked

notify()sleptresume()unblocked

start()

stop()

Page 145: 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.

Three threads exampleclass 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"); }

}

Page 146: 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.

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();

} }

Page 147: 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.

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= 5Exit from A From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5Exit from B

Page 148: 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.

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= 5Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5Exit from BExit from A

Page 149: 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.

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()– {

• …

– }

Page 150: 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.

150

the driver: 3rd 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()}

Page 151: 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.

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

account

Page 152: 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.

152

Monitor (shared object) exampleclass 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. }}

Page 153: 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.

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

Page 154: 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.

Thread Priority Exampleclass 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"); }

}

Page 155: 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.

Thread Priority Exampleclass 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"); }}

Page 156: 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.

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.

Page 157: 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.

Strings

• Initializing a String is painlesss1 = “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.

Page 158: 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.

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.

Page 159: 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.

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)

Page 160: 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.

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

Page 161: 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.

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

Page 162: 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.

How to do I/O

import java.io.*;

• Open the stream

• Use the stream (read, write, or both)

• Close the stream

Page 163: 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.

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

openuseclose

Page 164: 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.

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

openuseclose

Page 165: 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.

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

openuseclose

Page 166: 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.

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

openuseclose

Page 167: 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.

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)

openuseclose

Page 168: 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.

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);

openuseclose

Page 169: 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.

Reading lines

String s;s = bufferedReader.readLine( );

• A BufferedReader will return null if there is nothing more to read

openuseclose

Page 170: 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.

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!

openuseclose

Page 171: 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.

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

Page 172: 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.

My LineReader class

class LineReader { BufferedReader bufferedReader;

LineReader(String fileName) {...}

String readLine( ) {...}

void close( ) {...}}

Page 173: 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.

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 Exceptions

Page 174: 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.

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); }

Page 175: 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.

readLine

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

Page 176: 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.

close

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

Page 177: 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.

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

Page 178: 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.

The LineWriter class

class LineWriter { PrintWriter printWriter;

LineWriter(String fileName) {...}

void writeLine(String line) {...}

void close( ) {...}}

Page 179: 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.

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); } }

Page 180: 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.

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

Page 181: 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.

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)

Page 182: 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.

writeLine

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

Page 183: 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.

close

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

Page 184: 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.

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

Page 185: 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.

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

Page 186: 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.

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

Page 187: 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.

Writing objects to a file

ObjectOutputStream objectOut = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream(fileName)));

objectOut.writeObject(serializableObject);

objectOut.close( );

openuseclose

Page 188: 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.

Reading objects from a file

ObjectInputStream objectIn = new ObjectInputStream( new BufferedInputStream( new FileInputStream(fileName)));

myObject = (itsType)objectIn.readObject( );

objectIn.close( );

openuseclose