CS2311-oops_EEE.ppt

Embed Size (px)

Citation preview

  • 7/27/2019 CS2311-oops_EEE.ppt

    1/189

    CS2311 OBJECT ORIENTED

    PROGRAMMING

  • 7/27/2019 CS2311-oops_EEE.ppt

    2/189

    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 largerobjects polymorphism

    use code transparently for all types of same class of object

    i.e., morph one object into another object within same hierarchy

  • 7/27/2019 CS2311-oops_EEE.ppt

    3/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    4/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    5/189

    Sample Hello.cpp

    #include

    #include

    using namespace std;main() {

    cout

  • 7/27/2019 CS2311-oops_EEE.ppt

    6/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    7/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    8/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    9/189

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

  • 7/27/2019 CS2311-oops_EEE.ppt

    10/189

    Program structure

    just like in C

    program is a collection of functions anddeclarations

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    11/189

    Arrays

    similar to C

    dynamic memory allocation handled using new anddelete 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

  • 7/27/2019 CS2311-oops_EEE.ppt

    12/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    13/189

    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 aint *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

  • 7/27/2019 CS2311-oops_EEE.ppt

    14/189

    UNIT-II

    CLASSES AND OBJECTS

  • 7/27/2019 CS2311-oops_EEE.ppt

    15/189

    Classes and Objects

    Class:It is defined as blueprint or it is a

    collection of objects

    Objects:is an instance of a class

  • 7/27/2019 CS2311-oops_EEE.ppt

    16/189

    Declaring Class

    Almost like struct, the default privacy specification is privatewhereas

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    17/189

    Classes: function overloading and

    overridingoverloading:

    when you use the same name for functions with differentsignatures

    functions in derived class supercede any functions in

    base class with the same nameoverriding:

    when you change the behavior of base-class function ina derived class

    DONT OVERRIDE BASE-CLASS FUNCTIONS!! because compiler can invoke wrong version by mistake

  • 7/27/2019 CS2311-oops_EEE.ppt

    18/189

    Access specifiers

    public

    public members can be accessed from any function

    private members

    can only be accessed by classs own members and byfriends (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

  • 7/27/2019 CS2311-oops_EEE.ppt

    19/189

    Constructors and destructors

    constructors are called ctors in C++

    take the same name as the class in which theyare defined, like in Java

    destructors are called dtors in C++

    take the same name as the class in which theyare 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

  • 7/27/2019 CS2311-oops_EEE.ppt

    20/189

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

    ...}

  • 7/27/2019 CS2311-oops_EEE.ppt

    21/189

    Operator overloading

    Most operators can be overloaded in cpp

    Treated as functions

    But its important to understand how theyreally work

  • 7/27/2019 CS2311-oops_EEE.ppt

    22/189

    LIST OF OPERATORS

    +

    ~

    -

    !

    =

    *

    /=

    +=

    >

    &&

    ++

    []

    () new

    delete

    new[] ->

    >>=

  • 7/27/2019 CS2311-oops_EEE.ppt

    23/189

    Operators which cant be

    overloaded

    .

    .*

    ::

    ?:

  • 7/27/2019 CS2311-oops_EEE.ppt

    24/189

    Types of overloading

    Unary overloading

    Binary overloading

  • 7/27/2019 CS2311-oops_EEE.ppt

    25/189

    Inheritance

    Objects are often defined in terms of hierarchical classeswith a base class and one or more levels of classes thatinherit from the classes that are above it in the hierarchy.

    For instance, graphics objects might be defined asfollows:

  • 7/27/2019 CS2311-oops_EEE.ppt

    26/189

    Inheritance (continued)

    class A : base class access specifierB

    {

    member access specifier(s):

    ... member data and member function(s);

    ...

    }

    Valid access specifiers include public, private, andprotected

  • 7/27/2019 CS2311-oops_EEE.ppt

    27/189

    Syntax for Inheritance

    classderivedClass : publicbaseClass {

    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

    thoseof the base class (as when some base members are to be redefined)

  • 7/27/2019 CS2311-oops_EEE.ppt

    28/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    29/189

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

    };

  • 7/27/2019 CS2311-oops_EEE.ppt

    30/189

    More on Inheritance Syntax

    classderivedClass : protectedbaseClass { };

    // Effect: all public members inherited from baseClass are

    // now protected members ofderivedClass

    classderivedClass : privatebaseClass { };// Effect: all public and protected members inherited from

    // baseClass are now private members ofderivedClass

    Multiple inheritance A class can inherit several classesat once:

    classderivedClass:publicbaseClass1,publicbaseClass2{ };

    Remark: Not recommended

  • 7/27/2019 CS2311-oops_EEE.ppt

    31/189

    Virtual Functions

    class Object3D {

    virtual void intersect(Ray *r, Hit *h);

    };

    class Sphere : public Object3D {

    virtual void intersect(Ray *r, Hit *h);

    };

    myObject->intersect(ray, hit);

    If a superclass has virtual functions, the correct subclass

    version will automatically be selected

    Sphere *mySphere = new Sphere();

    Object3D *myObject = mySphere;

    A superclass pointer can reference a subclass object

    Actually calls

    Sphere::intersect

    Superclass

    Subclass

  • 7/27/2019 CS2311-oops_EEE.ppt

    32/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    33/189

    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 ofthe object.

    E.g. the message displayDetails() of

    the Person class should givedifferent results when send to aStudent object (e.g. the enrolment

    number).

  • 7/27/2019 CS2311-oops_EEE.ppt

    34/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    35/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    36/189

    Iostream Basics

    > is "get from" operator

    Three standard streams: cout, cin, cerrstd::cin >> x;

    std::cout

  • 7/27/2019 CS2311-oops_EEE.ppt

    37/189

    C++ Input/Output Library

    The basic data type for I/O in C++ is the stream. C++ incorporates acomplex hierarchy of stream classes. The most basic streamclasses are the standard input/output streams:

    istream cin built-in input stream variable; by default hooked tokeyboard

    ostream cout built-in output stream variable; by default hooked toconsole

    header file: C++ also provides stream types for reading from and writing to files: ifstream inFile; // input file stream object ofstream outFile; // output file stream object

    header file:

  • 7/27/2019 CS2311-oops_EEE.ppt

    38/189

    Standard Stream Objects

    cin istream class, tied to (connected to) thestandard input device (keyboard)

    cout ostream class, tied to standard outputdevice

    cerr ostream class, standard error output,unbuffered

    clog ostream class, also to standard error,

    buffered

  • 7/27/2019 CS2311-oops_EEE.ppt

    39/189

    Unformatted I/O

    cout.write(buffer, SIZE)

    cin.read(buffer, SIZE)

    The memory contents pointed by buffer isread/write.

    In formatted I/O, contents are translated

    into printable ASCII sequence

  • 7/27/2019 CS2311-oops_EEE.ppt

    40/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    41/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    42/189

    Read in a File

    #include

    #include

    ifstream fileobj(f.dat, ios::in); // create

    input file object

    fileobj >> data; // read from file

    ifstream is derived class of istream

    C.f. Fig. 14.7

  • 7/27/2019 CS2311-oops_EEE.ppt

    43/189

    Open and Close File

    Using scope rule

    {

    ofstream myfile(dat.d,

    ios::out);

    myfile

  • 7/27/2019 CS2311-oops_EEE.ppt

    44/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    45/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    46/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    47/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    48/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    49/189

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

  • 7/27/2019 CS2311-oops_EEE.ppt

    50/189

    Other Error Handling Techniquescont

    Test for the error condition

    issue an error message and call exit

    pass error code to environment

    setjump and longjump

    in jump out of deeply nested function calls back to an error handler. dangerous - unwinds the stack without calling destructors for

    automatic objects (more later)

    specific errors some have dedicated capabilities for handling them

    ifnew fails to allocate memory new_handler function executes todeal with problem

  • 7/27/2019 CS2311-oops_EEE.ppt

    51/189

    1 // Fig. 13.1: fig13_01.cpp

    2 // A simple exception handling example

  • 7/27/2019 CS2311-oops_EEE.ppt

    52/189

    1. Class definition

    1.1 Function definition

    2 // A simple exception handling example.

    3 // Checking for a divide-by-zero exception.

    4 #include

    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 {

    13public:

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

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

    17private:

    18 const char *message;

    19 };

    20

    21 // Definition of function quotient. Demonstrates throwing22 // 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 ifdenominator == 0

  • 7/27/2019 CS2311-oops_EEE.ppt

    53/189

    1 // Fig. 13.1: fig13_01.cpp

    2 // A simple exception handling example.

  • 7/27/2019 CS2311-oops_EEE.ppt

    54/189

    1. Class definition

    1.1 Function definition

    2 // A simple exception handling example.

    3 // Checking for a divide-by-zero exception.

    4 #include

    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 {

    13public:

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

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

    17private:

    18 const char *message;

    19 };

    20

    21 // Definition of function quotient. Demonstrates throwing22 // 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 ifdenominator == 0

  • 7/27/2019 CS2311-oops_EEE.ppt

    55/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    56/189

    UNIT-IV

    AN OVERVIEW OF JAVA

  • 7/27/2019 CS2311-oops_EEE.ppt

    57/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    58/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    59/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    60/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    61/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    62/189

    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) toachieve this

    Dynamic

    java is designed to adapt to evolving environment

    libraries can freely add new methods and instance variableswithout 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 t e in runtime

  • 7/27/2019 CS2311-oops_EEE.ppt

    63/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    64/189

    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!

  • 7/27/2019 CS2311-oops_EEE.ppt

    65/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    66/189

    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.

  • 7/27/2019 CS2311-oops_EEE.ppt

    67/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    68/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    69/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    70/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    71/189

    Language basics (2)

    Flow of control if, if-else, if-else if

    switch

    for, while, do-while

    break continue

  • 7/27/2019 CS2311-oops_EEE.ppt

    72/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    73/189

    Conditional Statements

    Relational operators

    The boolean condition in an if else statement is often expressed as atest of a relationship between two variables.

    Is x equal to y?

    Is xgreater than or equal to 0?

    Is xless than size?

    Is xnot 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 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)

  • 7/27/2019 CS2311-oops_EEE.ppt

    74/189

    Conditional Statements

  • 7/27/2019 CS2311-oops_EEE.ppt

    75/189

    Example

    import java.util.Scanner; //needed for input stream classes

    publicclass ConditionalStatementExample { publicstaticvoid 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.

  • 7/27/2019 CS2311-oops_EEE.ppt

    76/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    77/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    78/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    79/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    80/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    81/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    82/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    83/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    84/189

    Addi M th d t Cl Ci l

  • 7/27/2019 CS2311-oops_EEE.ppt

    85/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    86/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    87/189

    C ti bj t f l

  • 7/27/2019 CS2311-oops_EEE.ppt

    88/189

    Creating objects of a class

    Objects are created dynamically using thenewkeyword.

    aCircle and bCircle refer to Circle objects

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

  • 7/27/2019 CS2311-oops_EEE.ppt

    89/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    90/189

    A i Obj t/Ci l D t

  • 7/27/2019 CS2311-oops_EEE.ppt

    91/189

    Accessing Object/Circle Data

    Similar to C syntax for accessing datadefined in a structure.

    Circle aCircle = new Circle();

    aCircle.x = 2.0 // initialize center and radius

    aCircle.y = 2.0

    aCircle.r = 1.0

    ObjectName.VariableNameObjectName.MethodName(parameter-list)

  • 7/27/2019 CS2311-oops_EEE.ppt

    92/189

    Using Circle Class

  • 7/27/2019 CS2311-oops_EEE.ppt

    93/189

    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 fieldaCircle.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 MyMainRadius=5.0 Area=78.5Radius=5.0 Circumference =31.400000000000002

    Inheritance

  • 7/27/2019 CS2311-oops_EEE.ppt

    94/189

    94

    Inheritance

    Inheritance allows a software developer to derive a newclass from an existing one

    The existing class is called theparent class orsuperclass

    The derived class is called the child class orsubclass.

    Creates an is-a relationship

    The subclass is a more

    specific version of the

    Original

    (Rememberhas-a is

    aggregation.)

    Book

    NovelDictionary

    Mystery History

    Inheritance

  • 7/27/2019 CS2311-oops_EEE.ppt

    95/189

    Inheritance

    The child class inherits the methods and data defined forthe 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 thedesign, implementation, and testing of the existing

    software

    Deriving Subclasses

  • 7/27/2019 CS2311-oops_EEE.ppt

    96/189

    96

    Deriving Subclasses

    In Java, we use the reserved wordextends to establish an inheritance

    relationship

    class Dictionary extends Book {

    // class contents}

    Dictionary webster = new Dictionary();webster.message(); Number of pages: 1500

  • 7/27/2019 CS2311-oops_EEE.ppt

    97/189

    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 definitions: 52500

    Definitions per page: 35

  • 7/27/2019 CS2311-oops_EEE.ppt

    98/189

    The protected Modifier

  • 7/27/2019 CS2311-oops_EEE.ppt

    99/189

    99

    The protected Modifier

    Visibility modifiers determine which class members areinherited 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

    The protected Modifier

  • 7/27/2019 CS2311-oops_EEE.ppt

    100/189

    100

    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

    The super Reference

  • 7/27/2019 CS2311-oops_EEE.ppt

    101/189

    101

    The super Reference

    Constructors are not inherited, eventhough they have public visibility

    Yet we often want to use the parent'sconstructor to set up the "parent's part" of

    the object

    The super reference can be used to referto the parent class, and often is used to

    invoke the parent's constructor

    The super Reference

  • 7/27/2019 CS2311-oops_EEE.ppt

    102/189

    The super Reference

    A childs constructor is responsible forcalling the parents constructor

    The first line of a childs constructor shoulduse the super reference to call the

    parents constructor

    The super reference can also be used toreference other variables and methods

    defined in the parents class

  • 7/27/2019 CS2311-oops_EEE.ppt

    103/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    104/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    105/189

    Overriding

  • 7/27/2019 CS2311-oops_EEE.ppt

    106/189

    Overriding

    A parent method can be invoked explicitly using thesuper 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;

  • 7/27/2019 CS2311-oops_EEE.ppt

    107/189

    Book(int numPages) {pages = numPages;

    }

    public void message() {System.out.println(Number ofpages: + 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

  • 7/27/2019 CS2311-oops_EEE.ppt

    108/189

    108

    Overloading vs. Overriding

    data

    Overriding lets you define Don't confuse the concepts ofoverloading and overriding

    Overloading deals with multiple methods with the samename in the same class, but with different signatures

    Overriding deals with two methods, one in a parent classand one in a child class, that have the same signature

    Overloading lets you define a similar operation indifferent ways for different a similar operation in differentways for different object types

  • 7/27/2019 CS2311-oops_EEE.ppt

    109/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    110/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    111/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    112/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    113/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    114/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    115/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    116/189

  • 7/27/2019 CS2311-oops_EEE.ppt

    117/189

    Example

  • 7/27/2019 CS2311-oops_EEE.ppt

    118/189

    Example

    Files:

    Driver.java DriverFiles:

    Circle.java

    Rectangle.java

    OtherShape.java

    Files:

    PublicClass1.java

    PublicClass2.java

    Circle

    Rectangle

    OtherShape

    PublicClass1

    NonPublicClass1

    PublicClass2graphics

    graphics.shapes

    graphics.otherstuff

    Packages: Files: Classes:

  • 7/27/2019 CS2311-oops_EEE.ppt

    119/189

    Exception Definition

  • 7/27/2019 CS2311-oops_EEE.ppt

    120/189

    Exception Definition

    Treat exception as an object

    All exceptions are instances of a class extended from

    Throwableclass or its subclass.

    Generally, a programmer makes new exception class to

    extend the Exception class which is subclass of

    Throwable class.

  • 7/27/2019 CS2311-oops_EEE.ppt

    121/189

    Exception Definition

  • 7/27/2019 CS2311-oops_EEE.ppt

    122/189

    Exception Definition

    We can pass the object which contains amessage 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")

    }

    Hierarchical Structure of

    Th bl Cl

  • 7/27/2019 CS2311-oops_EEE.ppt

    123/189

    Throwable Class

    ObjectObject

    ThrowableThrowable

    ErrorError ExceptionException

    RuntimeExceptionRuntimeException

    ...

    ...

    ...

  • 7/27/2019 CS2311-oops_EEE.ppt

    124/189

    System-Defined Exception

  • 7/27/2019 CS2311-oops_EEE.ppt

    125/189

    System Defined Exception

    Raised implicitly by system because of illegal executionof program

    When cannot continue program execution any more

    Created by Java System automatically

    Exception extended from Error class andRuntimeException class

    System-Defined Exception

  • 7/27/2019 CS2311-oops_EEE.ppt

    126/189

    Syste e ed cept o

    IndexOutOfBoundsException :

    When beyond the bound of index in the object which useindex, 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 involveswait or notify method

    Programmer-Defined Exception

  • 7/27/2019 CS2311-oops_EEE.ppt

    127/189

    g p

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    128/189

    p

    Raised implicitly by system Raised explicitly by programmer

    throw Statement

    throw ThrowableObject; throw ThrowableObject;

    Throwable class or

    its sub class

    Throwable class or

    its sub class

  • 7/27/2019 CS2311-oops_EEE.ppt

    129/189

    Exception Occurrence

  • 7/27/2019 CS2311-oops_EEE.ppt

    130/189

    p

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

  • 7/27/2019 CS2311-oops_EEE.ppt

    131/189

    Exception Handling

  • 7/27/2019 CS2311-oops_EEE.ppt

    132/189

    p g

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    133/189

    public class Propagate {void orange() {int m = 25, i = 0;i = m / i;

    }void apple() {

    orange();}public static void main(String[] args) {

    Propagate p = new Propagate();p.apple();

    }

    }

    public class Propagate {void orange() {

    int m = 25, i = 0;i = m / i;

    }void apple() {

    orange();}public static void main(String[] args) {

    Propagate p = new Propagate(); p.apple();

    }

    }

    Output by Default Exception

    Handler

    Output by Default Exception

    Handler

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

    Exception Propagation

  • 7/27/2019 CS2311-oops_EEE.ppt

    134/189

    Explicit Description for possibility ofException Occurrence

    System-Defined Exception Do not need to announce the possibility ofexception occurrence

    Programmer-Defined Exception When it is not managed in correspond method, the

    exception type should be informed.

    Use the throws clause

    Exception Propagation

  • 7/27/2019 CS2311-oops_EEE.ppt

    135/189

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

    //

    }

    }

    What are Threads?

  • 7/27/2019 CS2311-oops_EEE.ppt

    136/189

    A piece of code that run in concurrent with otherthreads.

    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 ofcontrol Multithreading or Multithreaded

    Programming.

    A single threaded program

  • 7/27/2019 CS2311-oops_EEE.ppt

    137/189

    g p g

    class ABC{

    .

    public void main(..){

    ..

    }

    }

    begin

    body

    end

    A Multithreaded Program

  • 7/27/2019 CS2311-oops_EEE.ppt

    138/189

    g

    Main Thread

    Thread A Thread B Thread C

    start startstart

    Threads may switch or exchange data/results

    Java Threads

  • 7/27/2019 CS2311-oops_EEE.ppt

    139/189

    Java has built in thread support forMultithreading

    Synchronization

    Thread Scheduling

    Inter-Thread Communication: currentThread start setPriority

    yield run getPriority

    sleep stop suspend

    resume

    Java Garbage Collector is a low-priority thread

    Threading Mechanisms...

  • 7/27/2019 CS2311-oops_EEE.ppt

    140/189

    Create a class that extends the Thread class

    Create a class that implements the Runnableinterface

    1st method: Extending Threadclass

  • 7/27/2019 CS2311-oops_EEE.ppt

    141/189

    Threads are implemented as objects thatcontains 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

  • 7/27/2019 CS2311-oops_EEE.ppt

    142/189

    142

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

    2nd method: Threads by implementingRunnable interface

  • 7/27/2019 CS2311-oops_EEE.ppt

    143/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    144/189

    144

    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

    Life Cycle of Thread

  • 7/27/2019 CS2311-oops_EEE.ppt

    145/189

    145

    new

    runnable non-runnable

    dead

    wait()

    sleep()

    suspend()

    blocked

    notify()

    slept

    resume()

    unblocked

    start()

    stop()

    Three threads example

  • 7/27/2019 CS2311-oops_EEE.ppt

    146/189

    class A extends Thread{

    public void run()

    {

    for(int i=1;i

  • 7/27/2019 CS2311-oops_EEE.ppt

    147/189

    for(int k=1;k

  • 7/27/2019 CS2311-oops_EEE.ppt

    148/189

    [C:\jdk1.3\bin] threads [1:76] java ThreadTest

    From ThreadA: i= 1From 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= 2From 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= 4From ThreadB: j= 5

    Exit from B

    Run2

  • 7/27/2019 CS2311-oops_EEE.ppt

    149/189

    [C:\jdk1.3\bin] threads [1:77] java ThreadTest

    From ThreadA: i= 1From 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= 3From 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= 5Exit from B

    Exit from A

    Shared Resources

  • 7/27/2019 CS2311-oops_EEE.ppt

    150/189

    If one thread tries to read the data and otherthread tries to update the same date, it leads toinconsistent 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

  • 7/27/2019 CS2311-oops_EEE.ppt

    151/189

    151

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

    }

    Program with 3 threads andshared object

    l M Th d i l t R bl {

  • 7/27/2019 CS2311-oops_EEE.ppt

    152/189

    152

    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

    Monitor (shared object) example

  • 7/27/2019 CS2311-oops_EEE.ppt

    153/189

    153

    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.

    }

    }

    Thread Priority

  • 7/27/2019 CS2311-oops_EEE.ppt

    154/189

    In Java, each thread is assigned priority, whichaffects 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 Exampleclass A extends Thread

    {

  • 7/27/2019 CS2311-oops_EEE.ppt

    155/189

    public void run()

    {

    System.out.println("Thread A started");

    for(int i=1;i

  • 7/27/2019 CS2311-oops_EEE.ppt

    156/189

    public void run()

    {

    System.out.println("Thread C started");

    for(int k=1;k

  • 7/27/2019 CS2311-oops_EEE.ppt

    157/189

    Java provides a class definition for a type calledString

    Since the String class is part of the java.langpackage, 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 Javaconvention for classnames.

    Strings

  • 7/27/2019 CS2311-oops_EEE.ppt

    158/189

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

    newoperator required to create memory for new

    String object.

    String methods

  • 7/27/2019 CS2311-oops_EEE.ppt

    159/189

    Given a String objectwe can then access anypublicString methodorinstance 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, butthe above analogy is a good start.

    String Examples

  • 7/27/2019 CS2311-oops_EEE.ppt

    160/189

    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 procedurallanguage with structures? (homework)

    Streams

  • 7/27/2019 CS2311-oops_EEE.ppt

    161/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    162/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    163/189

    import java.io.*;

    Open the stream

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

    Why Java I/O is hardopen

    use

    close

  • 7/27/2019 CS2311-oops_EEE.ppt

    164/189

    Java I/O is very powerful, with anoverwhelming 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

    close

    Opening a streamopen

    use

    close

  • 7/27/2019 CS2311-oops_EEE.ppt

    165/189

    There is data external to your programthat you want to get, or you want to put

    data somewhere outside your program

    When you open a stream, you are makinga connection to that external place

    Once the connection is made, you forget

    about the external place and just use thestream

    close

    Example of opening a streamopen

    use

    close

  • 7/27/2019 CS2311-oops_EEE.ppt

    166/189

    A FileReader is a used to connect to a filethat 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

    close

    Using a streamopen

    use

    close

  • 7/27/2019 CS2311-oops_EEE.ppt

    167/189

    Some streams can be used only for input,others only for output, still others for both

    Usinga 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

    close

    Example of using a streamopen

    use

    close

  • 7/27/2019 CS2311-oops_EEE.ppt

    168/189

    int ch;ch = fileReader.read( );

    The fileReader.read() method reads onecharacter and returns it as an integer, or

    -1 if there are no more characters to read

    The meaning of the integer depends onthe file encoding (ASCII, Unicode, other)

    close

    Manipulating the input dataopen

    use

    close

  • 7/27/2019 CS2311-oops_EEE.ppt

    169/189

    Reading characters as integers isntusually what you want to do

    A BufferedReaderwill convert integers to

    characters; it can also read whole lines The constructor forBufferedReader takes

    a FileReader parameter:

    BufferedReader bufferedReader =new BufferedReader(fileReader);

    close

    Reading linesopen

    use

    close

  • 7/27/2019 CS2311-oops_EEE.ppt

    170/189

    String s;

    s = bufferedReader.readLine( );

    A BufferedReader will return nullif there

    is nothing more to read

    close

    Closingopen

    use

    close

  • 7/27/2019 CS2311-oops_EEE.ppt

    171/189

    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 onestream open on the same file

    You must close a stream before you can

    open it again Always close your streams!

    close

    Text files

  • 7/27/2019 CS2311-oops_EEE.ppt

    172/189

    Text (.txt) files are the simplest kind of

    files

    text files can be used by many differentprograms

    Formatted text files (such as.docfiles)

    also contain binary formatting information

    Only programs that know the secret

    code can make sense formatted text

    files

    My LineReader class

  • 7/27/2019 CS2311-oops_EEE.ppt

    173/189

    class LineReader {

    BufferedReader bufferedReader;

    LineReader(String fileName) {...}

    String readLine( ) {...}

    void close( ) {...}

    }

    Basics of the LineReaderconstructor

  • 7/27/2019 CS2311-oops_EEE.ppt

    174/189

    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, weneed to catch possible Exceptions

    The full LineReaderconstructor

  • 7/27/2019 CS2311-oops_EEE.ppt

    175/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    176/189

    String readLine( ) {

    try {

    return bufferedReader.readLine( );}

    catch(IOException e) {

    e.printStackTrace( );

    }return null;

    }

    close

  • 7/27/2019 CS2311-oops_EEE.ppt

    177/189

    void close() {

    try {

    bufferedReader.close( );

    }

    catch(IOException e) { }

    }

    How did I figure that out?

  • 7/27/2019 CS2311-oops_EEE.ppt

    178/189

    I wanted to read lines from a file

    I found a readLine method in the

    BufferedReader class The constructor forBufferedReader takes a

    Reader as an argument

    An InputStreamReader is a kind ofReader A FileReaderis a kind ofInputStreamReader

    The LineWriter class

  • 7/27/2019 CS2311-oops_EEE.ppt

    179/189

    class LineWriter {

    PrintWriter printWriter;

    LineWriter(String fileName) {...}

    void writeLine(String line) {...}

    void close( ) {...}

    }

    The constructor forLineWriter

  • 7/27/2019 CS2311-oops_EEE.ppt

    180/189

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    181/189

    When you put information into a buffered

    output stream, it goes into a buffer

    The buffer may not be written out rightaway

    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

  • 7/27/2019 CS2311-oops_EEE.ppt

    182/189

    Buffers are automatically flushed when

    the program ends normally

    Usually it is your responsibility to flushbuffers if the program does not end

    normally

    PrintWriter can do the flushing for you

    public PrintWriter(OutputStream out,

    boolean autoFlush)

    writeLine

  • 7/27/2019 CS2311-oops_EEE.ppt

    183/189

    void writeLine(String line) {

    printWriter.println(line);

    }

    close

  • 7/27/2019 CS2311-oops_EEE.ppt

    184/189

    void close( ) {

    printWriter.flush( );

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

    }

    Serialization

  • 7/27/2019 CS2311-oops_EEE.ppt

    185/189

    You can also read and write objects tofiles

    Object I/O goes by the awkward name of

    serialization Serialization in other languages can be

    verydifficult, because objects may contain

    references to other objects Java makes serialization (almost) easy

  • 7/27/2019 CS2311-oops_EEE.ppt

    186/189

    Implementing the Serializableinterface

  • 7/27/2019 CS2311-oops_EEE.ppt

    187/189

    To implement an interface means to define allthe 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

    Writing objects to a fileopen

    use

    close

  • 7/27/2019 CS2311-oops_EEE.ppt

    188/189

    ObjectOutputStream objectOut =

    new ObjectOutputStream(

    new BufferedOutputStream(

    new FileOutputStream(fileName)));

    objectOut.writeObject(serializableObject);

    objectOut.close( );

    Reading objects from a fileopen

    use

    close

  • 7/27/2019 CS2311-oops_EEE.ppt

    189/189

    ObjectInputStream objectIn =

    new ObjectInputStream(

    new BufferedInputStream(

    new FileInputStream(fileName)));

    myObject = (itsType)objectIn.readObject( );