Sei sulla pagina 1di 189

CS2311 OBJECT ORIENTED PROGRAMMING

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

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

Disadvantages
disadvantages of C++ over Java: Java protects you from making mistakes that C/C++ dont, as youve 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

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

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

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

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

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 dont use it!!!)

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

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

Defining c++ functions


a functions 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

Pointers and References


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

refa = *p + 1; // a is assigned value of *p=7 plus 1

UNIT-II

CLASSES AND OBJECTS

Classes and Objects


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

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

Classes: function overloading and overriding


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

Access specifiers
public public members can be accessed from any function private members can only be accessed by classs own members and by friends (see ahead) Protected Class members, derived, and friends. access violations when you dont obey the rules... can be listed in any order can be repeated

Constructors and destructors


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

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

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

LIST OF OPERATORS
+ ~ ! = * /= += << >>

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

Operators which cant be overloaded


.
.* :: ?:

Types of overloading
Unary overloading Binary overloading

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:

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

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)

Hierarchy

Example of Inherited Classes


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

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

Virtual Functions
A superclass pointer can reference a subclass object
Sphere *mySphere = new Sphere(); Object3D *myObject = mySphere;

If a superclass has virtual functions, the correct subclass version will automatically be selected
Superclass Subclass class Object3D { virtual void intersect(Ray *r, Hit *h); }; class Sphere : public Object3D { virtual void intersect(Ray *r, Hit *h); }; myObject->intersect(ray, hit);

Actually calls
Sphere::intersect

Pure Virtual Functions


A pure virtual function has a prototype, but no definition. Used when a default implementation does not make sense.
class Object3D { virtual void intersect(Ray *r, Hit *h) = 0; };

A class with a pure virtual function is called a pure virtual class and cannot be instantiated. (However, its subclasses can).

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

UNIT-III

IO STREAMS

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

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;

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>

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

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

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

Write in a File
#include <iostream> #include <fstream> ofstream fileobj(f.dat, ios::out);
file object

// create output

fileobj << data;

// output to file

ofstream is derived class from ostream

Read in a File
#include <iostream> #include <fstream> ifstream fileobj(f.dat, ios::in);
input file object

C.f. Fig. 14.7

// create

fileobj >> data;

// read from file

ifstream is derived class of istream

Open and Close File


Using scope rule
{ ofstream myfile(dat.d, ios::out); myfile << x; } ofstream myfile; myfile.open(dat.d, ios::out); myfile << x; myfile.close();

Explicit open and close

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

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

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

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

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

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

Other Error-Handling Techniques cont


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

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

1 2 3 4 5 6 7 8 9

// Fig. 13.1: fig13_01.cpp // A simple exception handling example. // Checking for a divide-by-zero exception. #include <iostream> using std::cout; using std::cin; using std::endl;

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 15 16 18 19 }; 20 DivideByZeroException() : message( "attempted to divide by zero" ) { } const char *what() const { return message; } const char *message;

17 private:

21 // Definition of function quotient. Demonstrates throwing 23 double quotient( int numerator, int denominator ) 24 { 25 26 27 28 29 } if ( denominator == 0 ) throw DivideByZeroException();

1. Class definition

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

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

1.1 Function definition

return static_cast< double > ( numerator ) / denominator;

1 2 3 4 5 6 7 8 9

// Fig. 13.1: fig13_01.cpp // A simple exception handling example. // Checking for a divide-by-zero exception. #include <iostream> using std::cout; using std::cin; using std::endl;

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 15 16 18 19 }; 20 DivideByZeroException() : message( "attempted to divide by zero" ) { } const char *what() const { return message; } const char *message;

17 private:

21 // Definition of function quotient. Demonstrates throwing 23 double quotient( int numerator, int denominator ) 24 { 25 26 27 28 29 } if ( denominator == 0 ) throw DivideByZeroException();

1. Class definition

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

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

1.1 Function definition

return static_cast< double > ( numerator ) / denominator;

1 2 3 4 5 6 7 8 9

// Fig. 13.1: fig13_01.cpp // A simple exception handling example. // Checking for a divide-by-zero exception. #include <iostream> using std::cout; using std::cin; using std::endl;

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 15 16 18 19 }; 20 DivideByZeroException() : message( "attempted to divide by zero" ) { } const char *what() const { return message; } const char *message;

17 private:

21 // Definition of function quotient. Demonstrates throwing 23 double quotient( int numerator, int denominator ) 24 { 25 26 27 28 29 } if ( denominator == 0 ) throw DivideByZeroException();

1. Class definition

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

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

1.1 Function definition

return static_cast< double > ( numerator ) / denominator;

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

try block encloses code that may throw an exception, along with code that should not execute if an exception occurs.

1.2 Initialize variables 2. Input data


catch block follows try block, and contains exception-handling code.

cout << "\nEnter two integers (end-of-file to end): ";

UNIT-IV

AN OVERVIEW OF JAVA

History of a Young Java


1992 Oak for a PDA on a SPARC (*7) 1995 Official release as Java Internet 1997 picoJava Suns 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 ;-)

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

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

Java Features (2)


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

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

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

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!

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

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.

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 declarations and initializations: int x; variable x=5; int[] intArray;
boolean b = true; Frame win = new Frame(); String x = how are you?; intArray = new int[2]; intArray[0] = 12; intArray[1] = 6; Person pArray = new Person[10];

Java system overview

Java Primitive Data Types


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

JVM Data Types


reference int long float double Pointer to an object or array 32-bit integer (signed) 64-bit integer (signed) 32-bit floating-point (IEEE 754-1985) 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

Language basics (2)


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

Conditional Statements
The if else statement Form of the if else statement
Expression that evaluates to true or false

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

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? == <= < > >= !=
(x == y) (x >= 0) (x < size) (x != 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

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

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

System.out.println(The absolute value is: + theInteger);

Conditional Statements
Programming style
public static void main(String [ ] args) { //list of statements indented 2 to 4 spaces int num1, num2, num3 = 5; num1 = 3 * num3 % 7; num2 = 5 * num3 % 11; //which number is larger if (num1 >= num2) { num1 += num3; }
2 to 4 spaces

Main block

Block of stmts. contained in if -- block

System.out.println(The larger pair is num1, num3); else { num2 += num3; } } Block of stmts. contained in else -- block

System.out.println(The larger pair is num2, num3);

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

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) If the condition is satisfied, the program returns return A; from this function call. Only scores less than 90 else are evaluated further inside this function. if (testScore >= 80) return B; else if (testScore >= 70) return C; By convention, each if and else block is else //testScore < 70 indented 2 to 4 spaces. return F: }

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

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.

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

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:
class ClassName [extends SuperClassName] { [fields declaration] [methods declaration] }

Bare bone class no fields, no methods public class Circle { // my circle class }

Adding Fields: Class Circle with fields


Add fields
public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle }

The fields (data) are also called the instance varaibles.

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

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() { Method Body return 3.14 * r * r; } }

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;

Class of Circle cont.


aCircle, bCircle simply refers to a Circle object, not an object itself.
aCircle bCircle

null

null

Points to nothing (Null Reference)

Points to nothing (Null Reference)

Creating objects of a class


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

Creating objects of a class


aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; Before Assignment aCircle bCircle Before Assignment aCircle bCircle

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.

Accessing Object/Circle Data


Similar to C syntax for accessing data defined in a structure.
ObjectName.VariableName ObjectName.MethodName(parameter-list)

Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0

Executing Methods in Object/Circle


Using Object Methods:
sent message to aCircle

Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area();

Using Circle Class


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

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. Book Creates an is-a relationship The subclass is a more specific version of the Dictionary Novel Original (Remember has-a is Mystery History aggregation.)

94

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

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

96

Dictionary webster = new Dictionary(); webster.message(); webster.defMessage();

Number of pages: 1500 Number of definitions: 52500 Definitions per page: 35

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

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

The protected Modifier


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

99

The protected Modifier


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

100

The super Reference


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

The super Reference


A childs constructor is responsible for calling the parents constructor The first line of a childs constructor should use the super reference to call the parents constructor The super reference can also be used to reference other variables and methods defined in the parents class

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

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.

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 childs version overrides the parents version in favor of its own. Signature: methods name along with number, type, and order of its parameters The new method must have the same signature as the parent's method, but can have a different body The type of the object executing the method determines which version of the method is invoked
105

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

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

Overloading vs. Overriding


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

Class Hierarchies
A child class of one parent can be the parent of another child, forming a class hierarchy Book
Dictionary Novel

Mystery

Romance

109

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

The Object Class


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

111

The Object Class


The Object class contains a few useful methods, which are inherited by all classes For example, the toString method is defined in the Object class Every time we have defined toString, we have actually been overriding an existing definition The toString method in the Object class is defined to return a string that contains the name of the objects 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

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

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

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

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

Class Access and Packages


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

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

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

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.

Exception Definition
class classUserErr UserErrextends extendsException Exception { {} } class classUserClass UserClass{ { UserErr UserErrx x= =new newUserErr(); UserErr(); // //... ... if if(val (val< <1) 1)throw throwx; x; } }

Exception Definition
We can pass the object which contains a message for the exception in string form

class classUserErr UserErrextends extendsException Exception{ { UserErr(String // UserErr(Strings) s) super(s); super(s); //constructor constructor } } class classUserClass UserClass{ { // //... ... if if(val (val< <1) 1)throw thrownew newUserErr("user UserErr("userexception exceptionthrow throwmessage") message") } }

Hierarchical Structure of Throwable Class


Object Object Throwable Throwable Error Error Exception Exception RuntimeException RuntimeException

...

...

...

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

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

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

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

Exception Occurrence
Raised implicitly by system Raised explicitly by programmer throw Statement throw throw ThrowableObject; ThrowableObject;

Throwable Throwableclass classor or its itssub subclass class

Exception Occurrence
class classThrowStatement ThrowStatementextends extendsException Exception { { public static void exp(int ptr) { public static void exp(int ptr) { if if(ptr (ptr== ==0) 0) throw thrownew newNullPointerException(); NullPointerException(); } } public publicstatic staticvoid voidmain(String[] main(String[]args) args){ { int i = 0; int i = 0; ThrowStatement.exp(i); ThrowStatement.exp(i); } } } }

java.lang.NullPointerException java.lang.NullPointerException at atThrowStatement.exp(ThrowStatement.java:4) ThrowStatement.exp(ThrowStatement.java:4) at atThrowStatement.main(ThrowStatement.java:8) ThrowStatement.main(ThrowStatement.java:8)

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

Exception Handling
try-catch-finally Statement Check and Handle the Exception
try try{{

// // }}catch catch(ExceptionType1 (ExceptionType1 identifier) identifier){{ // // }}catch catch(ExceptionType2 (ExceptionType2identifier) identifier){{ // // }}finally finally {{ // // }}

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

Exception Propagation
public public class class Propagate Propagate{{ void void orange() orange(){{ ArithmeticException ArithmeticExceptionOccurred Occurred int m = 25, i = 0; int m = 25, i = 0; ii= =m m//i; i; }} void void apple() apple(){{ orange(); orange(); }} public publicstatic staticvoid voidmain(String[] main(String[]args) args){{ Propagate Propagatepp= =new newPropagate(); Propagate(); p.apple(); Output p.apple(); Outputby byDefault DefaultException Exception }} Handler Handler }}
java.lang.ArithmeticException: //by java.lang.ArithmeticException: byzero zero at atPropagate.orange(Propagate.java:4) Propagate.orange(Propagate.java:4) at atPropagate.apple(Propagate.java:8) Propagate.apple(Propagate.java:8) at atPropagate.main(Propagate.java:11) Propagate.main(Propagate.java:11)

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

Exception Propagation
class class MyException MyExceptionextends extendsException Exception{{}} public publicclass classClassA ClassA{{ // // public publicvoid voidmethodA() methodA()throws throwsMyException MyException{{ // // if if(someErrCondition()) (someErrCondition()) throw thrownew newMyException(); MyException(); // // }} }}

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.

A single threaded program


class ABC { .
public void main(..) { .. }
begin

body end

A Multithreaded Program
Main Thread

start

start

start

Thread A

Thread B

Thread C

Threads may switch or exchange data/results

Java Threads
Java has built in thread support for Multithreading Synchronization Thread Scheduling Inter-Thread Communication:
currentThread yield sleep resume start run stop setPriority getPriority suspend

Java Garbage Collector is a low-priority thread

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

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

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

142

2nd method: Threads by implementing Runnable interface


class MyThread implements Runnable { ..... public void run() { // thread body of execution } } Creating Object: MyThread myObject = new MyThread(); Creating Thread Object: Thread thr1 = new Thread( myObject ); Start Execution: thr1.start();

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

Life Cycle of Thread


new
start() wait() sleep() suspend() blocked

runnable
stop() notify() slept resume() unblocked

non-runnable

dead

145

Three threads example


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

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

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

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

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

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


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

accoun t

152

Monitor (shared object) example


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

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

Thread Priority Example


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

Thread Priority Example


class C extends Thread { public void run() { System.out.println("Thread C started"); for(int k=1;k<=4;k++) { System.out.println("\t From ThreadC: k= "+k); } System.out.println("Exit from C"); } } class ThreadPriority { public static void main(String args[]) { A threadA=new A(); B threadB=new B(); C threadC=new C(); threadC.setPriority(Thread.MAX_PRIORITY); threadB.setPriority(threadA.getPriority()+1); threadA.setPriority(Thread.MIN_PRIORITY); System.out.println("Started Thread A"); threadA.start(); System.out.println("Started Thread B"); threadB.start(); System.out.println("Started Thread C"); threadC.start(); System.out.println("End of main thread"); } }

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.

Strings
Initializing a String is painless
s1 = This is some java String;

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

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

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)

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

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

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

open use close

Why Java I/O is hard

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

open use close

Opening a stream

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

open use close

Example of opening a stream

A FileReader is a used to connect to a file that will be used for input:


FileReader fileReader = new FileReader(fileName);

The fileName specifies where the (external) file is to be found You never use fileName again; instead, you use fileReader

open use close

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 its not usually that simple--you need to manipulate the data in some way as it comes in or goes out

open use close

Example of using a stream

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

open use close

Manipulating the input data

Reading characters as integers isnt usually what you want to do A BufferedReader will convert integers to characters; it can also read whole lines The constructor for BufferedReader takes a FileReader parameter:
BufferedReader bufferedReader = new BufferedReader(fileReader);

open use close

Reading lines

String s; s = bufferedReader.readLine( ); A BufferedReader will return null if there is nothing more to read

open use close

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!

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

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

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

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

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

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

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

The LineWriter class


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

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

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

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)

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

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

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

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

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

open use close

Writing objects to a file

ObjectOutputStream objectOut = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream(fileName))); objectOut.writeObject(serializableObject); objectOut.close( );

open use close

Reading objects from a file

ObjectInputStream objectIn = new ObjectInputStream( new BufferedInputStream( new FileInputStream(fileName))); myObject = (itsType)objectIn.readObject( ); objectIn.close( );

Potrebbero piacerti anche