OOP Lectures

Embed Size (px)

Citation preview

  • 8/8/2019 OOP Lectures

    1/52

    Object Oriented Programming2nd Year

    Computer & System EngineeringDepartment

    Dr. Khaled Nagi

    WS 2007/08

  • 8/8/2019 OOP Lectures

    2/52

    What is Java?

    Java is a high-level, 3rd generation programming language, like C, Fortran, Smalltalk,Perl,

    Java shares much of C's syntax, however, it is not C. Knowing how to program in C may help (ordisturb!) programming in Java!

    Java is a platform for application development

    Java solves the problem of platform-independence by using byte code.

    The Java compiler does not produce native executable code for a particular machine. Instead itproduces a byte code format.

    The Java interpreter then reads the byte code and translates it into the native language of the hostmachine on the fly.

    Since the byte code is completely platform independent, only the interpreter and a few nativelibraries need to be ported.

    The rest of the runtime environment including the compiler and most of the class libraries are writtenin Java.

    All these pieces, the javac compiler, the java interpreter, the Java programming language, and moreare collectively referred to as Java.

  • 8/8/2019 OOP Lectures

    3/52

    What is Java?

    Java is object-oriented programming language.

    In object-oriented programs data is represented by objects.Objects have two sections, fields (instance variables) and

    methods. Fields tell what an object is (values of its properties).

    Methods tell what an object does.(behavior of object)

    When a program is run messagesare passed back and

    forth between objects. When an object receives a message it responds accordingly

    as defined by its methods.

  • 8/8/2019 OOP Lectures

    4/52

    Differences between Java and C++

    Global variables:

    These are discouraged in Java. It is impossible to create a globalvariable that is outside of all classes. The only way to create a

    .

    GOTO:

    Java has no goto statement. It reserves the goto keyword to coverthe only sensible uses of it.

    Pointers:

    Java has no way to manipulate pointers (mem addresses) directly.You cannot convert an integer to a pointer, you cannotdereference an arbitrary memory address.

  • 8/8/2019 OOP Lectures

    5/52

    Differences between Java and C++

    Memory Allocation:

    Java has no malloc() or free() functions. Since every complex datastructure is an object, they are all allocated memory via the new

    . ,

    it is collected- automatically - for reuse by the system (garbagecollection/ recycle).

    Data types:

    Hardware-dependent data types such as int and char* lead to non-

    portable code. Java uses a standard size irrespective of the H/W. No header files.

    No preprocessor.

  • 8/8/2019 OOP Lectures

    6/52

    Differences between Java and C++

    Java does not have an explicit link phase.

    Java source code is divided into .java files (called compilationunits). The compiler compiles these into .class files containing byte

    .

    Exactly one .class file is produced for each class definition.

    The compiler searches the current directory and directoriesspecified in the CLASSPATH environment variable to find otherclasses explicitly referenced by name in each source code file.

    Classes that were unknown to a program when it was compiledcan be loaded into it at runtime.

    Java is inherently multi-threaded.

    A single Java program can have many different threads executingindependently and continuously.

  • 8/8/2019 OOP Lectures

    7/52

    The Hello World Application

    // Example Java program (single line comment)/* This is a multi-line comment

    Type this program using text (ASCII) editor, save it under the nameHelloWorld.java, then compile it using javac HelloWorld.java. This willroduce HelloWorld.class file which can be run usin ava HelloWorld

    */class HelloWorld {

    public static void main (String args[]) {System.out.println("Hello World!");

    }}

    Java is case sensitive. Java is a free-form language. White spaces separate tokens.

    Hello World!

  • 8/8/2019 OOP Lectures

    8/52

    Javadoc Documentation

    javadocis a tool to extract special comment tags in Java programs. The output of javadoc is an HTML file. All of the javadoc commands occur only within /** and */. There are two rimar wa s to use avadoc:

    embed HTML, or use doc tags.

    Doc tags are commands that start with a @ and are placed at thebeginning of a comment line. (A leading *, however, is ignored.)

    There are three types of comment documentation, which correspondto the element the comment precedes: class, variable, or method.

  • 8/8/2019 OOP Lectures

    9/52

    Javadoc Documentation

    //HelloWorld.java/** The first example program.* Displays a string Hello World!.* @author your-name* @author www.company.com* version 2.0

    Class comment,precedes the class

    definition

    */public class HelloWorld {

    /** Sole entry point to class & application* @param args array of string arguments* @return No return value* @exception exceptions No exceptions thrown* @see System.out*/

    public static void main(String[] args) {System.out.println("Hello World!");}

    }

    Methodcomment,precedes

    the methoddefinition

    Hyperlink!

  • 8/8/2019 OOP Lectures

    10/52

    Reserved Keywords

  • 8/8/2019 OOP Lectures

    11/52

    Java Programming Style

    In Java, every thing is an object.

    You manipulate an object using a referenceto it.

    You create an object by first create a reference.

    If you do not initialize it when created, the Javacompiler will put the reference = null.

    Identifiers in Java are case sensitiveand only $ and_special characters are allowed.

  • 8/8/2019 OOP Lectures

    12/52

    Java Programming Style

    Naming conventions

    public methods and variables have a leading lowercase(nextItem, currentValue, getTime)

    private and local identifiers have lower case with mixedunderscore (next_time, current_value, temp_position)

    final variables that represent contants use all upper case(GREEN, FRIDAY, MAXSTUDENT)

    class names starts with upper case (String, HelloWorld,MaterialClass)

  • 8/8/2019 OOP Lectures

    13/52

    Special case: Primitive Types

    primitive types that we use quite often inprogramming have special treatment. They areautomatic variables not reference. (i.e. not objects)

    The variable holds the value, and it is placed on thestackso its much more efficient than using new.

    Java determines the size of each primitive type.These sizes dont change from one machine

    architecture to another as they do in mostlanguages.

    All numerictypes are signed.

  • 8/8/2019 OOP Lectures

    14/52

    Primitive Types

  • 8/8/2019 OOP Lectures

    15/52

    Literals -- Examples

  • 8/8/2019 OOP Lectures

    16/52

    Special Escape Sequence

  • 8/8/2019 OOP Lectures

    17/52

    Variables

    A variable is defined by the combination of an identifier, a typeand a scope.

    type identifier [=value][, identifier [=value]];

    ava var a es are va on y rom e po n w ere ey are

    declared till the end of the enclosing compound statement. No variable hiding is allowed.

    Automatic type conversion is done when widening orpromotion. However, narrowing must explicitly be done.

    int i; byte b = 100; i = b; -------Automaticint i =100; byte b = (byte)i; ----Explicit

  • 8/8/2019 OOP Lectures

    18/52

    Arrays

    Array type is orthogonalto the type system. Arrays are always initializedand range checkingis done at run-time. Array objects have intrinsic lengthmember variable. Multidimensional arrays can have variable lengths. xamp es:

    int [] month_days; //int month_days[]; int [][]var_matrix;month_days = new int[12]; var_matrix = new int [4][];month_days[0] = 31; var_matrix[0]= new int [5];month_days[1] = 28; var_matrix[1]= {10,20,30}; var_matrix[2]= new int [7];month_days[11] = 31; var_matrix[3]= new int [10];

    int [] month_days = {31,28,31,30,31,30,31,31,30,31,30,31};

  • 8/8/2019 OOP Lectures

    19/52

    Operators

    An operator takes one or more arguments and produces avalue. It may modifies its arguments (side effect)

    Almost all operators work only with primitives. = == =

    (reference to objects). the String class supports + and +=.

    Assignment operator for objects are called aliasing To compare contents of objects use the special method

    equals() that exist with every object.

    You must override it to function correctly, otherwise the defaultworks with the reference.

  • 8/8/2019 OOP Lectures

    20/52

    Operators

    Shift operators and bit-wise logical operators work only forprimitive integral types.

    If you shift a char, byte, or short, it will be promoted to int before

    low-order bits of the right-hand side will be used. If youre operating on a long, youll get a long result. Only the six

    low-order bits of the right-hand side will be used.

    Ternary if-else operator (?:)

    boolean-exp ? value0 : value1

    The sole place that the commaoperator is used in Java is in forloops.

    Java has no sizeof() operator.

  • 8/8/2019 OOP Lectures

    21/52

    Execution Control

    if-else

    if (Boolean-expression) statement [else statement]

    return

    Iteration

    while(Boolean-expression) statement

    do statement while(Boolean-expression);

    for(initialization; Boolean-expression; step) statement

    Example:

    for(int i = 0, j = 1; i < 10 && j != 11; i++, j++)

    Inside the body of any of the iteration statements you cancontrol the flow of the loop by using break and continue.

  • 8/8/2019 OOP Lectures

    22/52

    Execution Control

    switch(integral-selector) {case integral-value1 : statement; [break;]case integral-value2 : statement; [break;]

    case integral-value3 : statement; [break;]case integral-value4 : statement; [break;]case integral-value5 : statement; [break;]// ...

    default: statement;}

    switch is fall through

  • 8/8/2019 OOP Lectures

    23/52

    Classes

    A class is the basic element in OOPs. It defines theshape and behavior of an object.

    A constructoris a special method that is called.

    nothing. The name of the constructor method must match the

    name of the class. If you define no constructors, the compiler will make

    one for you (default constructor). More than one constructor can be defined as long as

    their signaturesare different.

  • 8/8/2019 OOP Lectures

    24/52

    This Keyword

    The this keyword usually means the current object

    A can be used only inside a method.

    called for. When used in a constructor followed by an argument

    list, it is an explicit call to the specified constructor.

    Can be used to refer to member data whenparameters have the same name as a member data.

  • 8/8/2019 OOP Lectures

    25/52

    Example

    class Point{ class Point3D extends Point{

    int x,y; int z;Point(int x, int y){ Point3D(int x, int y, int z){

    this.x = x; super(x,y);this.y = y; this.z = z;

    } }

    double distance(int x, int y){ double distance(int x, int y, int z){int dx = this.x x; int dx = this.x x;

    int dy = this.y y; int dy = this.y y;return Math.sqrt(dx*dx + dy*dy); int dz = this.z z;

    } return Math.sqrt(dx*dx + dy*dy + dz*dz);double distance(Point p){ }

    return distance(p.x, p.y); double distance(Point3D p){

    } return distance(p.x, p.y, p.z);} }

    double distance(int x; int y){double dx = this.x/z x;

    double dy = this.y/z y;return Math.sqrt(dx*dx + dy*dy);}

    }

  • 8/8/2019 OOP Lectures

    26/52

    Example

    class PointDistance {public static void main(String args[]) {

    Point3D p1 = new Point3D(30,40,10);Point3D P2 = new Point3D(0,0,0);Point p = new Point(4,6);System.out.println(p1= + p1.x + ,+ p1.y + ,+ p1.z);

    System.out.println(p2= + p2.x + ,+ p2.y + ,+ p2.z);System.out.println(p= + p.x + , + p.y);System.out.println(p1.distance(p2) = + p1.distance(p2));System.out.println(p1.distance(4,6) = + p1.distance(4,6));System.out.println(p1.distance(p) = + p1.distance(p));

    }

    } p1= 30,40,10p2= 0,0,0p= 4,6p1.distance(p2) = 50.99019513592785p1.distance(4,6) = 2.23606797749979p1.distance(p) = 2.23606797749979

    Method overridingDynamic binding

    Output

  • 8/8/2019 OOP Lectures

    27/52

    Dynamic Method Dispatch

    class A {void callme() {

    System.out.println(A);}

    }class B extends A{

    void callme() {System.out.println(B);

    }}class Dispatch{

    public static void main(String args[]){

    A a = new B();a.callme();

    }}

  • 8/8/2019 OOP Lectures

    28/52

    final

    final is a type modifier used to declare thatsubclasses are no longer allowed to override thevariable or method.

    final variablesare the same as static and usuallyused to create the equivalent of const in C++.

    Example

    final int RED=1;

    final int GREEN=2; final methodsprevents subclasses from overriding

    the method.

  • 8/8/2019 OOP Lectures

    29/52

    static

    static variables are treated as global withinthe class. It needs no object to access.

    static methods can be called outside thecontext of any instance.

    static blocks gets executed exactly once

    when the class is first loaded.

  • 8/8/2019 OOP Lectures

    30/52

    class StaticExample{static int a = 3;static int b;static void method(int x){

    system.out.println(x= +x);system.out.println(a= +a);

    system.out.println(b= +b);}static {

    system.out.println(static block initialized);b=a*4;

    }

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

    }

  • 8/8/2019 OOP Lectures

    31/52

    abstract

    The abstract keyword is used to declare subclasserresponsibility for methods implementations.

    An abstract class will define the structure of some.

    Any class which contains anyabstract method, must alsodeclared abstract.

    No direct instantiation of abstract class with the newoperator.

    No abstract constructors or abstract static methods. Any subclass of an abstract class must either implement all

    of the abstract methods in the superclass, or be itselfdeclared abstract.

  • 8/8/2019 OOP Lectures

    32/52

    abstract

    abstract class A{abstract void callme();void metoo(){

    System.out.println(inside As metoo method);}

    class B extends A{

    void callme(){System.out.println(inside Bs callme method);

    }}class TestAbsract{

    public static void main(String args[]){A a=new B();

    a.callme();a.metoo();}

    }

  • 8/8/2019 OOP Lectures

    33/52

    package & import Statements

    Packages are containers for classes that are used to manage theclass name space.

    Packages are stored in a hierarchical manner and are explicitlyimported into new class definitions.

    ava comp er uses e sys em rec or es o s ore pac ages.

    If you declare a class to be inside of a package, then the source file for thatclass must be stored in a directory with the same name as the package.

    The general form of a java source file is[package pkg1[.pkg2[]]];[import pkgr[.pkgt[]][.class_name|*]];

    ...[import pkgn[.pkgm[]][.class_name|*]];A single public class declaration;[any number of private class definition];

  • 8/8/2019 OOP Lectures

    34/52

    package & import Statements

    If package statement is not present, then all the classes end upin the default package which has no name.

    The import statement are used to bring certain classes, or.

    import java.lang.*; is implicitly considered at the top of allprograms.

    If a class with the same name exists in two different importedpackages, the compiler dictates that explicit naming must beused.

    CLASSPATH environment variable defines the root of all javapackages.

  • 8/8/2019 OOP Lectures

    35/52

    Access Protection

  • 8/8/2019 OOP Lectures

    36/52

    interface & implements Statements

    interface is the mechanism which is used to disconnect thedefinition of methods from the class hierarchy. interfaces are just like classes, but usually without instance

    abstract).

    If you declare variables in an interface, they will be treated as finalconstants.

    If an interface contains no methods, then any class which declaresthat it implements such an interface is actually importing theconstant variables into the class name space as final variables.

    Classes may implement any number of interfaces. A class implements an interface by implementing each method in

    the interface.

  • 8/8/2019 OOP Lectures

    37/52

    interface & implements Statments

    interface Packable{ public byte[] pack(){

    byte[] pack(); byte[] ret = new byte[8];void unpack(byte b[]); ret[0] = p(x,24); ret[4] = p(y,24);

    } ret[1] = p(x,16); ret[5] = p(y,16);class Point{ ret[2] = p(x,8); ret[6] = p(y,8);

    int x,y; ret[3] = p(x,0); ret[7] = p(y,0);

    Point(int x, int y){ return ret; }this.x = x; public void unpack(byte[] b){

    this.y = y; x=u(b[0],24)|u(b[1],16)|u(b[2],8)|u(b[3],0);} y= u(b[4],24)|u(b[5],16)|u(b[6],8)|u(b[7],0); }

    } public String toString(){class NewPoint extends Point implements Packable{ return NewPoint[ + x + , + y + ]; }

    NewPoint(int x; int y){ }

    super(x,y); class PointPack{} public static void main(String args[

    NewPoint(){ Packable p=new NewPoint(123456, 214748);this(0,0); byte[] packed = p.pack();

    } NewPoint p1 =new NewPoint();private byte p(int t, int n){ p1.unpack(packed);

    return (byte)((t>>n)&0xff); System.out.println(packed + = + p1;}

    }private int u(byte b, int n){

    return (b&0xff)

  • 8/8/2019 OOP Lectures

    38/52

    Sample of Java Classes:

    String and StringBuffer

    String and StringBuffer classes are built-in

    classes injava.lang package String represents unchangeablestrings.

    StringBuffer is a companion class that representsobjects of strings that can be manipulated aftercreation.

  • 8/8/2019 OOP Lectures

    39/52

    Sample of Java Classes:

    Constructors String s = new String(); //creates empty string

    char ch[] = {a, b, c, d, e, f}

    =

    String s1 = new String(ch,2,3); // creates cde byte ascii[]={65,66,67,68,69,70};

    String s2 = new String(ascii,0); //ABCDEF with hiByte=0

    String s3 = new String(ascii,0,2,3); // CDE with hiByte=0

    Special syntax String s = abcd;

    Member method: length() String s = abcd; System.out.println(s.length());

  • 8/8/2019 OOP Lectures

    40/52

    Sample of Java Classes:

    Concatenation + is overloaded

    int age;String s = He is + age + years old;

    int age;String s = new StringBuffer(He is).append(age).append(years old).toString();

    String conversion:Every class should override toString() method to get the required representation ofthe output.

  • 8/8/2019 OOP Lectures

    41/52

    Sample of Java Classes:

    Character Extraction

    String s = ABCDEF

    = .

    int start = 2;int end = 5;

    char buf[] = new char(end start);

    s.getChars(start, end, buf, 0);byte bbuf[] = new byte(end start);

    s.getByte (start, end, bbuf, 0); Extracts the chars fromthe string and place them

    into byte buffer after

    dropping the high orderbyte.

  • 8/8/2019 OOP Lectures

    42/52

    Sample of Java Classes:

    String Comparisonboolean equals(String s)boolean equalsIgnoreCase(String s)boolean re ionMatches(int offset, Strin other, int otheroffset, int len)boolean regionMatches(boolean ignorecase, int offset, String other, intotheroffset, int len)boolean startsWith(String s)boolean endsWith(String s)int compareTo(String s)int indexOf(char ch)int lastIndexOf(char ch)

    Note: == is used only to compare two object references

  • 8/8/2019 OOP Lectures

    43/52

    Sample of Java Classes:

    String Copy Modification

    Note: Return new string objects

    String substring(int start, int end)

    String concat(String s)

    String replace(char current, char newchar)

    String toLowerCase()

    String toUpperCase()

  • 8/8/2019 OOP Lectures

    44/52

    Exception Handling

    An exception is an abnormal condition that arises in a codesequence at run time.

    A java exception is an object that describes an exceptional.

    Exceptions can appear asynchronouslyin a method, or theycan be explicitlycreated and thrown to report some errorcondition to the calling method.

    If youre inside a method and you throw an exception (oranother method you call within this method throws an

    exception), that method will exit in the process of throwing. If you dont want a throw to exit the method, you can set up a

    special try block within that method to catch the exception.

  • 8/8/2019 OOP Lectures

    45/52

    General Form of Exception HandlingBlock

    try{

    //block of code

    } catch(ExceptionType1 e){

    // exception handler for ExceptionType1

    }catch(ExceptionType2 e){

    // exception handler ExceptionType2

    throw(e); // rethrow the exception

    }finally {// finally code

    }

  • 8/8/2019 OOP Lectures

    46/52

    Main Exception Types

  • 8/8/2019 OOP Lectures

    47/52

    How Exception Works

    When java runtime tries to execute the code of try block, and anabnormal condition occurs, the runtime stops the code and throws anexception object of the type representing the condition (error).

    The flow of code execution is interrupted and the current call-stack is.

    If no exception handler is found, the default handler is used whichprints out the Exception object and the stack trace of where theexception occurred.

    The scope of the catch clause is restricted to the immediatelypreceding try statement.

    The throw statement is used to explicitly throw an exception. The flow

    of execution stops immediately after the throw statement, and the nextstatement is not reached. The corresponding handler is executed.

  • 8/8/2019 OOP Lectures

    48/52

    Exception Specification (throws)

    To identify the list of possible exceptions that amethod might throw, the compiler dictating the use ofthe ke word throws.

    type method-name(arg-list) throws exception-list{} For all Exception subclasses, you have to declare

    which types a method will possibly throw.

    For Error or RuntimeException, the above rule doesnot apply.

  • 8/8/2019 OOP Lectures

    49/52

    finally

    The finally keyword is used to identify a blockof code that will always run no matter an

    or not.

    The finally block will be executed just beforea method returns to the caller.

    The finally block is used to perform clean-uptasks (destructor).

  • 8/8/2019 OOP Lectures

    50/52

    The finally clause is always executed.

    class ThreeException extends Exception {}public class FinallyWorks {

    static int count = 0;public static void main(String[] args) {

    while(true) {

    ThreeExceptionIn finally clauseNo exceptionIn finall clause

    try {

    if(count++ == 0) throw new ThreeException();System.out.println("No exception");

    } catch(ThreeException e) {System.err.println("ThreeException");

    } finally {System.err.println("In finally clause");if(count == 2) break; // out of "while"}

    }}

    }

  • 8/8/2019 OOP Lectures

    51/52

    Example

    class FinallyDemo{static void procedureA(){

    try{ System.out.println(inside A);throw new RuntimeException(Demo);

    } finally {System.out.println(As finally);}

    static void procedureB(){

    try{System.out.println(inside B);return;} finally {System.out.println(Bs finally);}

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

    try{ procedureA();} catch (Exception e){;

    System.out.println(e);}

    procedureB();}

    }

    inside AAs finally

    java.lang.RuntimeException: Demoinside BBs finally

  • 8/8/2019 OOP Lectures

    52/52

    Exercise

    Write a complete java code that illustratesthe various outcomes of code flow when

    atc ng an except on ns e t e met o .

    Catching an exception in a higher level.

    No catching of the exception.

    No exception generated.

    Your code should contain finally block.