02 Java Oop Class

Embed Size (px)

Citation preview

  • 8/8/2019 02 Java Oop Class

    1/104

  • 8/8/2019 02 Java Oop Class

    2/104

  • 8/8/2019 02 Java Oop Class

    3/104

  • 8/8/2019 02 Java Oop Class

    4/104

  • 8/8/2019 02 Java Oop Class

    5/104

  • 8/8/2019 02 Java Oop Class

    6/104

  • 8/8/2019 02 Java Oop Class

    7/104

    7

    Java OOP-class

    ClassesA class (e.g. , Dog) is a k ind of mo ld or temp late to crea te o bjects (e.g ., Mary and DooDoo)

    m old = = mo uldAn o bject is an instance of a c lass. The o bject belongs to that class

    Dog Dog

    r

    DogDooDoo

    Instance-of

    Dog

  • 8/8/2019 02 Java Oop Class

    8/104

    8

    Java OOP-class

    What Is an Obj ect?

    These rea l-wor ld o bjects all have states and behav iors .Defini tion: An o bject is a sof tware bundle of v ariables

    and re lated methods ( function ).

    A common vis ual represen tation of asof tware o bject.

  • 8/8/2019 02 Java Oop Class

    9/104

    9

    Java OOP-class

    Examp le: Bicyc leThe sof tware bicyc le's c urren t state:

    its speed is 10 mph, its peda l cadence is 9 0 rpm , and

    its curren t gear is the 5 th gear .

    The sof tware bicyc le wo uld also have me thods tobrake,change the pedal cadence, and change gears.

  • 8/8/2019 02 Java Oop Class

    10/104

    10

    Java OOP-class

    W hat Are Classes ?Defini tion:

    A class is a blueprin t or pro totypeDefines the varia bles and me thods common to all o bjects of a

    cer tain k ind.The Benefi ts of C lasses

    Reusa bility -- Sof tware programmers use the same c lass , and thesame code to crea te many o bjects.

  • 8/8/2019 02 Java Oop Class

    11/104

    11

    Java OOP-class

    Obj ects vs. Classes

    Obj ec ts:E.g. , a rea l car.

    Classes: or typesE.g. , BM W -500

    A Class i s a bluepr int o r t empla t e of s ome obj ec t s

    Obj ec t i s an In s t ance of s ome class.

    Obj ec t ( , ) -- (Var i able )

  • 8/8/2019 02 Java Oop Class

    12/104

    12

    Java OOP-class

    An bst r act Data Type (ADT ) is a user -defined data type that satisfies the fo llowing two condi tions: ( E ncapsulation + Info rm ationHiding )

    The represen tation of , and opera tions on, o bjects of the type aredefined in a sing le syn tactic unit; also, other program units cancrea te o bjects of the type.The r ep r esentation of objects of the type is hidden f r om thep r og r am units that use these objects , so the on ly opera tions(methods ) possi ble are those provided in the type's defini tion

    which are k nown as interfaces .

    ADT --- Data Abstraction

    ADT: =(f unction)

  • 8/8/2019 02 Java Oop Class

    13/104

    13

    Java OOP-class

    Encaps ulation ( )Hide the o bject's nucleus from o ther o bjects in the program .

    The imp lemen tation de tails can change a t any time wi thout affec ting o ther par ts of the program.

    It is an idea l represen tation of an o bject, butFor imp lemen tation or efficiency reasons , an o bject may wish to expose

    some of i ts var iables or hide some of i ts methods .

    Benefi ts:M odula r ity

    The so urce code for an o bject can be wri tten and main tained independen tly of the so urce code for o ther o bjects.

    Info rm ation hidingAn o bject has a p ublic in terface that other o bjects can use to comm unica tewith it.

  • 8/8/2019 02 Java Oop Class

    14/104

    14

    Java OOP-class

    Classes in Java

    A class -- is a temp late that descri bes the data and behavio rassocia ted wi th instances of that class .An object -- ins tantiate a c lass yo u crea te an object .An object is an ins tance of some class .The da ta associa ted wi th a class or o bject is s tored invar iables .The behavior associa ted wi th a c lass or o bject isimp lemen ted wi th methods .

    Methods are simi lar to the f unctions or proced ures in C.

  • 8/8/2019 02 Java Oop Class

    15/104

    15

    Java OOP-class

    public class Bicycle {

    private int speed = 10;

    private int pedalCadence = 90;

    private int currentGear = 5;

    // a constructor!

    public void brake() { /* ... */ } public void changePedalCadence(int x) { /* */ } public void changeGear(int x) { /* ... */ }

    }

    Class B icycle in Java

    Not all owed in C++ L anguage

  • 8/8/2019 02 Java Oop Class

    16/104

    16

    Java OOP-class

    Class HelloW or ld (Applet version)

    import java.applet.Applet;import java.awt.Graphics;

    public class HelloWorld extends Applet {public void paint(Graphics g) {

    g.drawString("Hello world!", 50, 25);}

    }

    inherit pplet

  • 8/8/2019 02 Java Oop Class

    17/104

    17

    Java OOP-class

    W hat Is Inheri tance ? (extends )Subclasses inherit va r iables and m ethods from s u perc lasses.

    States:Gear & Speed

    Behaviors:Brak e & Accelerate

    Subclasses canAdd va r iables and m ethods .Ove rr ide inheri ted m ethods .

    Benefi ts:Provide specia lized behaviors

    Reuse the code in the s u perc lassA bstract classes -- define "generic" behaviors.

  • 8/8/2019 02 Java Oop Class

    18/104

    18

    Java OOP-class

    Man k ind extends Anima lpublic class Animal {

    private int height = 0;private int weight = 0;public void talk( ) { System.out.println(Arhh");}

    }

    public class Mankind extends Animal {private int iq = 120;public void talk( ) { System.out.println("Hello");}

    }

    M ankind is-a Anima l

    Sho uld be indifferen t files

    One Java fi le can on ly have one p ubl ic c lass

  • 8/8/2019 02 Java Oop Class

    19/104

    19

    Java OOP-class

    Man k ind inheri ts Anima l (C++ )class Animal {

    int height = 0;int weight = 0;

    public:void talk( ) { System.out.println("Won");}

    } ;

    class Mankind :public Animal {private: int iq = 120;

    public: void talk( ) { System.out.println("Hello");}} ;

    Classescan bein samefile

    In C++ , ";" is req uired to termina te a c lass

  • 8/8/2019 02 Java Oop Class

    20/104

    20

    Java OOP-class

    Rec tang le Con tains Poin tpublic class Point {

    private int x = 0;private int y = 0;

    }

    public class Rectangle {private int width = 0;private int height = 0;private Point origin = new Point();

    }

    Sho uld be indifferen t files

    Car has-a W hee l

  • 8/8/2019 02 Java Oop Class

    21/104

    21

    Java OOP-class

    public class Point {private int x = 0;

    private int y = 0;

    // a constructor! public Point(int xxx, int y) {

    x = xxx;this.y = y;

    }}

    . . .Point p = new Point(44,78);

    Poin t and i t's const r ucto r

    this.ythis.x

  • 8/8/2019 02 Java Oop Class

    22/104

    22

    Java OOP-class

    Class may have many Cons tr uctorspubl i c class Rec t angle {

    int wi dth = 0;int h eight = 0;Point or igin ;// fo ur cons t ruc to rs

    publ i c Rec t angle () { or igin = new Point( 0, 0) ; }publ i c Rec t angle ( Point p) { or igin = p; }publ i c Rec t angle (int w, int h) { thi s (n ew Point( 0, 0), w, h) ; }publ i c Rec t angle ( Point p, int w, int h)

    { or igin = p; width = w; height = h; }

    // a metho d fo r moving th e rec t anglepubl i c voi d move(int x, int y) { or igin . x = x; or igin . y = y; }// a metho d fo r computing th e area of th e rec t anglepubl i c int area () { re t ur n wi dth * h eight ; }

    }

  • 8/8/2019 02 Java Oop Class

    23/104

    23

    Java OOP-class

    W hat Are Messages?Message in an o bject.Sof tware o bjects in terac t and comm unica te wi th each o ther by sending messages to each o ther.

    W hen o bject A wan ts o bject B to perform one of B's me thods , o bject A sends a message to o bject B.

  • 8/8/2019 02 Java Oop Class

    24/104

    24

    Java OOP-class

    Messaging

    Three componen ts comprise a message:1. The o bject to whom the message is addressed (Yo ur Bicyc le).2. The name of the me thod to perform (changeGears).3. Any parame ters needed by the me thod ( lowerGear).

    Benefi ts:Message passing s u ppor ts all interac tions between o bjects.Messages can be sen t and received between processes in the samemachine or in differen t machines.

    you rB icycle .changeGea r s(lowe r Gea r)

  • 8/8/2019 02 Java Oop Class

    25/104

    25

    Java OOP-class

    Obj ect-Orien ted Techno logy

    Obj ect-O rien ted Analysis ( OOA )Goa l: Unders tand the domain

    Obj ect-O rien ted Design ( OO D)Goa l: Design a so lution , a mode l of the domain in which thedesired ac tivities occ ur

    Obj ect-O rien ted Programming ( OO P)Goa l: Imp lemen t the so lution

    No te: A Good Design is 2/3 Before Yo u Hit the Key board

  • 8/8/2019 02 Java Oop Class

    26/104

    26

    Java OOP-class

    It's a process , not a wa terfa ll

    Design is an i tera tive ac tivi tyStar t in OOA, go to OO D, forge t some thing in OOAGet to OO P, rea lize yo u didn' t unders tand some thing and go back

    The s tages are there to iden tify emphasesFor examp le, OOA is T OTALLY Lang uage -Independen t

    Wat er f all m odel

    emphases = = emphas i s

  • 8/8/2019 02 Java Oop Class

    27/104

    27

    Java OOP-class

    O bject-Orien ted Analysis

    Step one: Brains torming Candida te ClassesW rite down a ll the o bjects that related

    Focus on the nounsGood o bjects have attributes and ser v ices

    Now , filter the candida tesDea l with the in terface later (No t par t of the domain)Are some candida tes attr ibutes of o thers?

    Are some subclasses of o thers? (Inheri tance)Are some instances of o thers?

  • 8/8/2019 02 Java Oop Class

    28/104

    28

    Java OOP-class

    OOA : CRC CardsStep two: W rite CRC cards and wor k thro ugh scenarios

    Class-Responsibility-Collabo r ato r Cards (C unningham and Bec k )Just 3x5 cards

    Dat a fi elds ( att r ib ut es )

    Although CRC is no t par t of UML , theyadd some very usef ul

    insigh ts thro ugho ut adeve lopmen t.

  • 8/8/2019 02 Java Oop Class

    29/104

    29

    Java OOP-class

    How to use CRC Cards

    Ma k e one for each candida te classInven t scenarios: W hat sho uld these o bjects do?Play the cards

    Lay down the card that star ts the scenarioW rite down i ts responsi bilityAdd co lla bora tor o bjects to he l p wi th that responsi bilityPic k u p cards as they leave the scenario

  • 8/8/2019 02 Java Oop Class

    30/104

    30

    Java OOP-class

    W hy CRC Cards?

    Hel p yo u iden tify o bjects and their responsi bilitiesHe l p yo u unders tand in terac tions between o bjects

    Cards form a usef ul record of ear ly design ac tivi tyCards wor k we ll in gro u p si tuations and are unders tanda ble bynon -technica l stak eho lders

  • 8/8/2019 02 Java Oop Class

    31/104

    31

    Java OOP-class

    Obj ect-Orien ted Design

    Step one: Crea te a UML c lass diagram of yo ur o bjec ts

    Step two: Crea te a de tailed descrip tion of theservices to be performed

    Peter Coad's "I am a Co unt. I k now how toincremen t "

    Activi ty, seq uence , or co lla bora tion UML diagrams

  • 8/8/2019 02 Java Oop Class

    32/104

    32

    Java OOP-class

    MD A-Mode l Driven Archi tecture?

    A New W ay to Specify and B uild Sys tems2001 OMG ( http://www.omg.org )

    U ML M odel ( )

    : Analysis , Design , Implemen tation , Dep loymen t, Main tenance , Evo lution & Integra tion wi th later sys tems (

    )

    R OI ( ):

    Programming lang uage y Ne twor k O pera ting Sys tem y Midd leware

  • 8/8/2019 02 Java Oop Class

    33/104

    33

    Java OOP-class

    Unified Mode ling Lang uage

    There have been O-O gur us for many yearsThree of them wor k ed toge ther to define UML (Threeamigos : Booch , Ru m baugh , J acobson )Has now been approved as a standard by the Obj ect Managemen t Gro u p (OMG)Very powerf ul, many forms of no tation

    It's even prova ble! (wi th OCL)

    htt p://www.UML.org

    am igos = f r iends

    htt p://www.omg.org

    (Object Const r ain Language )

  • 8/8/2019 02 Java Oop Class

    34/104

    34

    Java OOP-classHis tory of the UML( htt p://www. uml.org/ )

    Public Feedback

    Web - June 1996 Web - June 1996 UML 0.9UML 0.9

    Unified Method 0.8 Unified Method 0.8 OOPSLA 95 OOPSLA 95

    UML 1.0 UML 1.0 UML partnersUML partners

    OMG Acceptance, Nov 1997 Final submission to OMG, Sept 1997 First submission to OMG, Jan 1997

    OMG Acceptance, Nov 1997 Final submission to OMG, Sept 1997 First submission to OMG, Jan 1997

    UML 1.1UML 1.1

    UML 2.0 UML 2.0 Approved 2004 Approved 2004

    Minor revision 1999Minor revision 1999 UML 1.3UML 1.3

    UML 1.4UML 1.4Minor revision 2001Minor revision 2001

    OOSE Other methods OMT Booch method

    Minor revision 2003Minor revision 2003 UML 1.5 UML 1.5

  • 8/8/2019 02 Java Oop Class

    35/104

    35

    Java OOP-class

    UML Diagrams

    U se case diagramsF unctional behavio r of the syste m as seen by the use r .

    Class diagramsS tatic st r uctu r e of the syste m: Objects, Att r ibutes, andAssociations.

    Activity diagramsDyna m ic behavio r of a syste m , in pa r ticula r the wo r kflow, i.e. a flowcha r t.

    Seq uence diagramsDyna m ic behavio r between acto r s and syste m objects.

    Statechar t diagramsDyna m ic behavio r of an individual object as FS M ( ).

  • 8/8/2019 02 Java Oop Class

    36/104

    36

    Java OOP-class

    UML 12 Diagrams

    Behavior :Use CaseSeq uence

    Co lla bora tionState Char tActivi ty

    Str uctural:ClassComponen t

    Dep loymen tObj ect

    Mode l Managemen t:Pac k ages (c lass diagram con tains pac k ages)Subsys tems (c lass diagram con tains s ubsys tems)Mode ls (c lass diagram con tains mode ls)

  • 8/8/2019 02 Java Oop Class

    37/104

    37

    Java OOP-class

    So, W hat is UML?

    UML is a Unified Mode ling Lang uageUML is a se t of no tations , not a sing le me thodo logyMode ling is a way of thin k ing a bout the pro blems using

    mode ls organized aro und the rea l wor ld ideas.Res ulted from the convergence of no tations from threeleading Obj ect-O rien ted me thods:

    Booch method ( by Grady Booch)OMT ( by James R um baugh)OO SE ( by Ivar Jaco bson)

    Yo u can mode l 80% of mos t pro blems by using a bout 20% of the UML

    UML is a blueprint for building complex software

  • 8/8/2019 02 Java Oop Class

    38/104

    38

    Java OOP-class

    UML Core Conven tionsRec tang les are classes or ins tancesOvals are f unctions or use casesTypes are deno ted wi th non -under lined names

    SimpleWatch

    Firefighter

    Instances are deno ted wi th an under lined namesmyWatch:SimpleWatch

    Joe:Firefighter

    Diagrams are higraphs Nodes are en tities (e.g. c lasses , states)Arcs are re lationships among en tities (e.g. sender/receiver)Con tainmen t represen ts belonging (e.g. use cases in pac k age)

    Hig r aphs are anextension to thefami liar Direc tedGraph s tr ucturewhere nodes areconnec ted by

    edges to o ther nodes. Nodesrepresen t entitiesin some domain (inour case , classes ,

    pac k ages , methods , etc.).

  • 8/8/2019 02 Java Oop Class

    39/104

    39

    Java OOP-classU se Case Diagram examp les

    WatchUser WatchRepairPerson

    ReadTime

    SetTime

    ChangeBattery

    Actor

    Use case

    PackageSimpleWatch

    U se case diagrams represen t the f unctiona lity of the sys temfrom users poin t of view. ( wha t, how)

    A use casedoc

    umen

    ts

    theinterac tion between the

    system user and the sys tem.It is high ly de tailed indescri bing wha t is req uired but is free of mos t imp lemen tation de tails and

    cons train ts.

  • 8/8/2019 02 Java Oop Class

    40/104

    40

    Java OOP-class

    Class Diagram : a simp le W atch

    Batteryload()

    1

    2

    Timenow()

    PushButtonstatepush()release()

    1

    1

    1

    1

    1

    2

    blinkIdxblinkSeconds()blinkMinutes()blinkHours()stopBlinking()referesh()

    LCDDisplay

    SimpleWatch

    C lass

    Association

    Operations

    Class diagrams represen t the s tr ucture of the domain or sys tem

    Attributes

    Multiplicity

  • 8/8/2019 02 Java Oop Class

    41/104

    41

    Java OOP-classSeq uence DiagramObject

    Message Activation

    Seq uence diagrams represen t the behavior as in terac tionsIt shows seq uence of even ts for a par ticular use case

    blinkHours()

    blinkMinutes()

    incrementMinutes()refresh()

    commitNewTime()stopBlinking()

    pressButton1()

    pressButton 2 ()

    pressButtons1And 2 ()

    pressButton1()

    :WatchUser :Time:LCDDisplay:SimpleWatch

    Activation

    Collabo r ation Diag r am

    Obj ect diagram wi thnum bered messages

    Seq uence n um bers of messagesare nes ted by proced ure ca ll

  • 8/8/2019 02 Java Oop Class

    42/104

    42

    Java OOP-class

    button1& 2 Pressed

    button1& 2 Pressed

    button1Pressed

    button 2 Pressed

    button 2 Pressed

    button 2 Pressed

    button1Pressed

    button1& 2 Pressed Increment Minutes

    IncrementHours

    BlinkHours

    BlinkSeconds

    Blink Minutes

    IncrementSeconds

    StopBlinking

    State char t Diagrams for the wa tch

    StateInitial state

    Final state

    Transition

    Event

    FS M: F inite S tate M achine

  • 8/8/2019 02 Java Oop Class

    43/104

    43

    Java OOP-class

    Activi ty DiagramsAn ac tivi ty diagram shows f low con trol within a sys tem

    An ac tivi ty diagram is a specia l case of a state cha r t diag r amin which s tates are ac tivi ties (f unctions)Two types of s tates:

    A ct ion state:Canno t be decomposed any f ur ther Happens ins tantaneo usly wi th respec t to the leve l of a bstraction used in

    the mode lA ct ivi ty state:

    Can be decomposed f ur ther The ac tivi ty is mode led by ano ther ac tivity diagram

    Business process use case ;

    HandleIncident

    DocumentIncident

    ArchiveIncident

  • 8/8/2019 02 Java Oop Class

    44/104

    44

    Java OOP-class

    Classes in UMLClasses descri be o bjec ts

    Behavio ur (mem ber f unction signa ture / imp lemen tation)Proper ties (a ttri butes and associa tions)

    Associa tion , aggrega tion , dependency , and inheri tancerelationshipsMult iplici ty and naviga tion indica torsRole names

    Obj ec ts descri bed by c lasses co lla bora teClass re lations o bject relationsDependencies between c lasses

  • 8/8/2019 02 Java Oop Class

    45/104

    45

    Java OOP-class

    U ML ClassClass name

    Data mem bers

    (attri butes)

    Instance me thods

    Argumen tsReturn typesClass me thod (s tatic)

    Data mem bers , arg umen ts and me thods are specified byvisi bility name : type

    Visi bility shown as+ publ ic- priva te# pro tected

  • 8/8/2019 02 Java Oop Class

    46/104

    46

    Java OOP-class

    Class Att ri butes

    Att ri butes are the ins tance da ta mem bersand c lass da ta mem bers

    Class data m em be r s (under lined)

    are shared between a ll ins tances(o bjects) of a given c lass

    Data types shown af ter ":"

    Visi bility shown as+ publ ic- priva te# pro tected

    Att ri butecompar tmen t

    visi bility name : type

    Class name

  • 8/8/2019 02 Java Oop Class

    47/104

    47

    Java OOP-class

    Class O pera tions (In terface)

    O pera tions are the c lassme thods wi th their arg umen tand re turn types

    Publ ic (+) opera tions define theclass in terface

    Class me thods ( under lined)can on ly access to c lass da tamem bers , no need for a c lassins tance (o bject)

    O pera tionscompar tmen t

  • 8/8/2019 02 Java Oop Class

    48/104

    48

    Java OOP-class

    Temp late C lasses

    Generic c lasses depending on parame trised types

    Type parame ter(s)

    O pera tions compar tmen tas usual, but may have

    type parame ter ins tead of concre te type

  • 8/8/2019 02 Java Oop Class

    49/104

    49

    Java OOP-class

    Class Inheri tance

    Base c lass or s u per c lass

    Derived c lass or s ubclass

    Arrow shows direc tionof dependency ( B inheri ts A)

    B inheri ts A's in terface , behavio ur and da ta mem bersB can ex tend A, i.e. add newdata mem bers or mem ber f unctionsB depends on A,A k nows no thing a bout B

  • 8/8/2019 02 Java Oop Class

    50/104

    50

    Java OOP-class

    Mult iple Inheri tance ( Java )

    The derived c lass inheri tsinterface , behavio ur anddata mem bers of a ll its base c lasses

    Extension and overridingwor k s as before

    B imp lemen ts the in terface A andis a lso a "co unta ble" c lass since i tinheri ts class Co unta ble

    extends

    imp lemen ts

    class B ex tends Co unta ble imp lemen ts A { /* */ }

  • 8/8/2019 02 Java Oop Class

    51/104

    51

    Java OOP-class

    How can two c lasses be re lated?G eneral iz at ion-spec ial iz at ion or IsA

    NamedBox Is A BoxDiagram: Triang le on the re lationship line

    A ssoc iat ion or HasABox Has A PenDiagram: J ust a re lationship lineA ggregat ion is a part-whole relationship

    Diagram: Diamond on the line

    Dependency or TalksToDependency is sor t of temporary Has A

    Diagram: Dashed line in UML

  • 8/8/2019 02 Java Oop Class

    52/104

    52

    Java OOP-class

    Recommended Boo k :

    UML Dis tilledSerio us O-O designers D O use UMLUML Dis tilled by M a r tin F owle r is a grea t pract ical introd uction to UMLOfficia l UML book series p ubl ished by Addison -W esley

    htt p://www.omg.org

  • 8/8/2019 02 Java Oop Class

    53/104

    53

    Java OOP-class

    UML Too ls

    Mos t comp lete tool: Rationa l Rose , htt p://www.ra tiona l.comLots of o thers

    Toge ther by Obj ect Interna tiona l, htt p://www.oi.comBOO ST (Basic Obj ect-Orien ted S u ppor t Too l) by Noe l Rappin , avai la ble on CD/Co W e bArgo -UML , Obj ectPlant, Posiden , etc.

  • 8/8/2019 02 Java Oop Class

    54/104

    54

    Java OOP-class

    O O F eatu r es

    Encaps ulationInforma tion Hiding (Da ta Hiding)

    Inhe r itancePoly m or phis m

    Obj ect Based

    Obj ect O r iented( )( )

    F or S oftwa r e Reuse

  • 8/8/2019 02 Java Oop Class

    55/104

    55

    Java OOP-class

    OO featu r esE ncapsulationInfo rm ation Hiding

    The concep t of a bstrac tion isf undamen tal in programming

    Sub program / f unc tion

    p r ocess abst r action

    ADT

    Data abst r actionS oftwa r e Reuse

    :Inhe r itancePoly m or phis m

    : /

  • 8/8/2019 02 Java Oop Class

    56/104

    56

    Java OOP-class

    Class elemen ts

  • 8/8/2019 02 Java Oop Class

    57/104

    57

    Java OOP-class

    Cons tr uctors

    F or purpose of initialization objects have specialmethods called constructors.

    To write a constructor you must adhere to two rules :1. The method name must exactly match the class

    name.

    2. There must not be a return type declared for themethod.

    Java has NO destructor.

  • 8/8/2019 02 Java Oop Class

    58/104

    58

    Java OOP-class

    The Defa ult Cons tr uctor

    E very class has a constructor .

    If you don t write one Java provides one for you . This

    constructor takes no arguments and has an empty body.

    ? What If you write one constructor ?

  • 8/8/2019 02 Java Oop Class

    59/104

    59

    Java OOP-class

    S tr uct in C/C++

    #include st r uct S tudent {

    long sid ;

    cha r na m e[9] ; /* B ig5 */

    float sco r e[13] ; /* 13 */}; /* */int m ain( ) {

    st r uct S tudent x ; /* C++ C99 st r uct */

    x.sid = 123 ; st r cpy(x.na m e, " " ) ; /* *//* loop x.sco r e[?] */

    }

    W hy using s tr uct ?Java has no str uct

  • 8/8/2019 02 Java Oop Class

    60/104

    60

    Java OOP-class

    S tr uct vs. Class in C++ (1/2 )

    #include class S tudent { // st r uct S tudent { ?

    long sid ;

    };

    int m ain( ) {S tudent x ;

    x.sid = 123 ; // co m pile , access not allowedcout

  • 8/8/2019 02 Java Oop Class

    61/104

    61

    Java OOP-class

    S tr uct vs. Class in C++ (2/2 )#include class S tudent { // p r ivate :

    long sid ;

    public : showNu m be r ( ) { r etu r n sid ; }setId( long xx ) { sid = xx ; }

    };

    int m ain( ) {S tudent x, y ;

    x.setId(123 ); // OK, public function setId( )

    cout

  • 8/8/2019 02 Java Oop Class

    62/104

    62

    Java OOP-class

    Class(Object ) Const r ucto r 1/4 (C++ )#include class S tudent { // p r ivate :

    long sid ;

    public : showNu m be r ( ) { r etu r n sid ; }setId( long xx ) { sid = xx ; }

    };

    int m ain( ) {S tudent x, m , n ;S tudent y(456 ); // Err or

    x.setId(123 ); r etu r n 0 ;

    }Studen t y(456 ) ; !

    defa ult cons tr uctor

    defa ult cons tr uctor

  • 8/8/2019 02 Java Oop Class

    63/104

    63

    Java OOP-class

    Class(Object ) Const r ucto r 2/4 (C++ )#include class S tudent { // p r ivate :

    long sid ;

    public : showNu m be r ( ) { r etu r n sid ; }setId( long xx ) { sid = xx ; }

    S tudent(long x ) { sid = x ; }};

    int m ain( ) {S tudent x ; // Err orS tudent y(456 ); // OK nowx.setId(123 ); r etu r n 0 ;

    } Studen t y(456 ) ; OK

    cons tr uctor

    Studen t x; !defa ult cons tr uctor

    :

  • 8/8/2019 02 Java Oop Class

    64/104

    64

    Java OOP-class

    #include class S tudent { // p r ivate :

    long sid ;

    public : showNu m be r ( ) { r etu r n sid ; }setId( long x ) { sid = x ; }

    S tudent (long x =0 ) { sid = x ; }};

    int m ain( ) {S tudent x, y(456 ); // OK x.setId(123 ); r etu r n 0 ;

    }Studen t x;

    Defa ult

    Class(Object ) Const r ucto r 3/4 (C++ )

  • 8/8/2019 02 Java Oop Class

    65/104

    65

    Java OOP-class

    #include class S tudent { // p r ivate :

    long sid ;

    public : showNu m be r ( ) { r etu r n sid ; }setId( long xx ) { sid = xx ; }

    S tudent(long x ) { sid = x ; cout

  • 8/8/2019 02 Java Oop Class

    66/104

    66

    Java OOP-class

    More a bout Classes

    Proper ties:Sing le imp lemen tation inheri tance - extends

    The inheri ted c lass is ca lled su perc lass .

    Multiple in terface inheri tance - implements

    All classes inheri t from java. lang. ObjectScope: (nex t slide)

  • 8/8/2019 02 Java Oop Class

    67/104

    67

    Java OOP-class

    S cope

  • 8/8/2019 02 Java Oop Class

    68/104

    68

    Java OOP-class

    The Life Cyc le of an Obj ect Crea tion (I)Crea ting Obj ects

    Rectangle rect = new Rectangle();

    Dec laring an Obj ectObj ect dec lara tions can a lso appear a lone :

    Rectangle rect;

    In Java , classes and in terfaces can be used as da ta types.Decla r ations do not c r eate new objects.

    Instantiating an Obj ectThe new opera tor a lloca tes memory for a new o bject.The new opera tor req uires a arg umen t: a ca ll to a cons tr uctor.

    The new opera tor crea tes the o bject, and the cons tr uctor ini tializes i t.new Rectangle(100, 200);

    The new opera tor re turns a reference to the new ly crea ted o bject.Rectangle rect = new Rectangle(100,200);

    Af ter this s tatemen t, rect refers to a Rectangle o bject.

  • 8/8/2019 02 Java Oop Class

    69/104

    69

    Java OOP-class

    The Life Cyc le of an Obj ect -- Crea tion (II)

    Initializing an Obj ectCons tr uctors have the sa m e na m e as the class and have no r etu r ntype .

    public Rectangle(Point p)

    public Rectangle(int w, int h)

    public Rectangle(Point p, int w, int h)public Rectangle()

    Examp le:Rectangle rect = new Rectangle(100, 200);

    Rectangle rect = new Rectangle(

    new Point(44,78));

    A cons tr uctor can tak es no arg umen ts, is ca lled a no-argument

    constructor .If a c lass does no t define any cons tr uctors , Java provides a no -argumen t cons tr uctor , called the default constructor.

  • 8/8/2019 02 Java Oop Class

    70/104

    70

    Java OOP-class

    The Life Cyc le of an Obj ect -- Access

    Using Obj ectsReferencing an Obj ect's Varia bles

    objectReference . variable

    Examp le:

    int areaOfRectangle = rect.height * rect.width;

    Calling an Obj ect's Me thodsobjectReference. methodName(); or objectReference. methodName(argumentList);

    Examp le:rect.move(15, 37);

    int areaOfRectangle =new Rectangle(100, 50).area();

  • 8/8/2019 02 Java Oop Class

    71/104

    71

    Java OOP-class

    The Life Cyc le of an Obj ect Clean u p

    Cleaning Up Un used Obj ectsAn o bject is e ligi ble for gar bage co llection when there are no morereferences to that o bject.The Gar bage Co llector

    Aut oma tica lly frees an o bject, if no t referenced. preven ts memory leak sclaimed de lay ~2 00ms for 4MBMar k-sweep gar bage co llector The gar bage co llector r uns in a low- priori ty thread.

    W hen the sys tem r uns o ut of memory.In response to a req uest from a Java program.W hen the sys tem is id le.

  • 8/8/2019 02 Java Oop Class

    72/104

    72

    Java OOP-class

    Fina liza tionW hen freeing an o bject, the sys tem wi ll call this firs t.The finalize method is a mem ber of the Object class.Imp lemen ting a finalize me thod to r elease r esou r ces that aren' t under the con trol of the ga r bage collecto r , such as na tive

    peers.Scenario: For a file o bject, when freed , need to close it.Pro blem: Ma k e the in terna l JVM imp lemen tation for memory managemen t very comp lica ted.Examp le

    public class Rectangle {public Point origin;

    . . .protected void finalize () throws Throwable {

    origin = null;super.finalize() ;

    }}

  • 8/8/2019 02 Java Oop Class

    73/104

    73

    Java OOP-class

    Examp le for Overriding (1/2)class Point {

    protected int x,y;

    Point (int x, int y) { this.x = x; this.y = y;}

    void draw (){System.out.println(Point at+x+,+y);

    };

    }

    Subclassing:class Cpoint extends Point {

    private Color c;

    Cpoint (int i, int j, Color c) {

    super (i,j);

    this.c =c;

    };void draw (){

    System.out.println(Color Point at + i + , + j + , + c);};

    }

  • 8/8/2019 02 Java Oop Class

    74/104

    74

    Java OOP-class

    Examp le for Overriding (2/2)class PointApp {

    public static void main() {

    Point p = new Point(5,5);

    Cpoint cp = new Cpoint(1,1,Red);

    p.draw();

    cp.draw(); p = cp; p.draw();

    // call Points draw() or Cpoint s draw()?}

    }

    Overr i ding overl oading !

  • 8/8/2019 02 Java Oop Class

    75/104

    75

    Java OOP-class

    Over loadingA Method's Name (f unction name)

    Java s u ppor ts me thod name overload ing so that mult iple me thods canshare the same name.

    class DataRenderer {

    void draw(String s) { . . . }

    void draw(int i) { . . . }

    void draw(float f) { . . . }

    }

    Ove r loaded methods are differen tiated by the nu m be r and type of thea r gu m ents .

    A subclass may override a me thod in i ts su perc lass.The overriding me thod m ust have the same name , return type, and parame ter list as the me thod i t overrides.

    Java opera to r overl oading

  • 8/8/2019 02 Java Oop Class

    76/104

    76

    Java OOP-class

    Abstrac t Classes in Java

    Abstrac t classes crea ted using the a bstrac t k eyword: publ ic a bstrac t class Mo torVehic le { }

    In an a bstrac t class , severa l a bstrac t methods are dec lared.

    - An a bstrac t method is no t imp lemen ted in the c lass , only dec lared. The body of the me thod is then imp lemen ted in s ubclass.

    - An a bstrac t method is decora ted wi th an ex tra a bstrac t k eyword.Abstrac t classes can no t be ins tantiated! So the fo llowing isillega l:

    Mo torVehic le m = new Mo torVehic le; // !//

    //

  • 8/8/2019 02 Java Oop Class

    77/104

    77

    Java OOP-class

    Abstrac t methods

    Abstrac t methods are dec lared but do no t con tain animp lemen tation.For examp le, the Mo torVehic le class may have an a bstrac t method gas( ):

    publ ic abst r act class Mo torVehic le { priva te do uble speed , maxSpeed;void accToMax( ) { speed = maxSpeed;} // !

    publ ic abst r act void gas( ); // ; C++ =0;/* */

    }So Mo torVehic le can N OT be ins tantiated

    (ie. , can no t be used to crea te an o bject.)

  • 8/8/2019 02 Java Oop Class

    78/104

    78

    Java OOP-class

    Examp le of Abstrac t Classes (1/2)

    Examp le:abstract class Stack {

    abstract void push(Object o);abstract Object pop();

    }

    public class ArrayStack extends Stack {.... // declare elems[] and top;void push(Object o) { elems[top++] = o; }Object pop() { return elems[--top]; }

    }

    class LinkedStack extends Stack {.... // declare ...void push(Object o) { .... }Object pop() { .... }

    }

  • 8/8/2019 02 Java Oop Class

    79/104

    79

    Java OOP-class

    Examp le of Abstrac t Classes (2/2)

    // ============================== Another file...static public int testStack(Stack s) { ....

    s.push(x); s.push(y);o1 = s.pop(); o 2 = s.pop();// check if o1 == y && o 2 == x.

    }...

    ArrayStack as = new ArrayStack();testStack(as) ;...

    J OOP l

  • 8/8/2019 02 Java Oop Class

    80/104

    80

    Java OOP-class

    I nterfacesDefines a se t of me thods that a c lass m ust imp lemen t

    An interface is lik e a class with no thing but a bstrac t methodsand fina l and s tatic fie lds (cons tants).An interface can a lso have fie lds, but the fie lds m ust bedec lared as fina l and static.All methods are a bstrac t imp lici tly.

    I nterface can be added to a c lass that is a lready a s ubclass of ano ther c lass. ( imp lemen ts)To dec lare an in terface:

    publ ic interface Impor tTax { publ ic do uble ca lculateTax( );

    }

    J OOP l

  • 8/8/2019 02 Java Oop Class

    81/104

    81

    Java OOP-class

    Examp le of I nterfaces (1/2)interface Stack {

    void push(Object o);

    Object pop();

    }

    public class ArrayStack implements Stack { .... // declare elems[] and top;void push(Object o) { elems[top++] = o; }Object pop() { return elems[--top]; }

    }

    class LinkedStack implements Stack {

    .... // declare ...void push(Object o) { .... }Object pop() { .... }

    }

    J OOP l

  • 8/8/2019 02 Java Oop Class

    82/104

    82

    Java OOP-class

    Examp le of I nterfaces (2/2)

    //============================== Another file

    ...

    static public int testStack(Stack s) { ....

    s.push(x); s.push(y);o1 = s.pop(); o2 = s.pop();

    // check if o1 == y && o2 == x.

    }

    ...

    ArrayStack as = new ArrayStack();

    testStack(as) ;...

    J OOP l

  • 8/8/2019 02 Java Oop Class

    83/104

    83

    Java OOP-class

    Difference between Abstrac t Class and I nterface

    An a bstrac t class is a c lass con taining severa l a bstrac t methods.Each a bstrac t method is prefixed wi th the k eyword a bstrac t.

    An a bstrac t class can no t be ins tantiated but can be ex tended(subclassed).An interface con tains on ly a bstrac t methods and cons tants.Each a bstrac t method is no t prefixed with the k eyword a bstrac t.

    An interface can on ly be imp lemen ted.

    Java OOP class

  • 8/8/2019 02 Java Oop Class

    84/104

    84

    Java OOP-class

    How C++ Dea ls wi th I nterfaces

    or Abstrac t ClassesUse vir tual f unctions:class Stack {

    virtual void push(void* o) = NULL;

    virtual void* pop() = NULL; // NULL 0}

    // C++ virtual = NULL; = 0;// = NULL; =0; virtual f unction pure vir tual f unction// Java virtual

    W hat are the in terna l designs?Key for the designs of C OM/DC OM (MicroSof t)

    Java OOP class

  • 8/8/2019 02 Java Oop Class

    85/104

    85

    Java OOP-class

    Examp le for C++class ArrayStack : Stack {

    .... // declare elems[] and top;void push(Object o) { elems[top++] = o; }Object pop() { return elems[--top]; }

    }class LinkedStack : Stack {

    .... // declare ...

    void push(Object o) { .... }Object pop() { .... }}============================== Another file...int testStack(Stack s) { ....

    s.push(x); s.push(y);o1 = s.pop(); o 2 = s.pop();// check if o1 == y && o 2 == x.

    }...

    ArrayStack as = new ArrayStack();testStack(as) ;...

    Java OOP class

  • 8/8/2019 02 Java Oop Class

    86/104

    86

    Java OOP-class

    Pac k ages and Li braryOrganize c lass na m e spaceHierarchica l division m ust be ref lected in direc tory s tr ucture, i.e. ,

    package cyc.sys ;import java.io.*;class Login { /* in fact, this is cyc.sys.Login */ }

    Defa ult pac k ages ( li brary) -- JDK java. lang - Obj ect, Thread , Excep tion , String ,...java.io - InputStream , Out putStream , ...java.ne t - Ne twor k ing

    su ppor t for Soc k et & URL -based o bjectsjava.aw t - Abstrac t window toolk it

    defines a simp le, restricted windowing APIjava. util - Hash ta ble, Vec tor , BitSet, Regexp , ..java. tools - Compi lation , De bugging , Doc umen tation

    Java OOP class

  • 8/8/2019 02 Java Oop Class

    87/104

    87

    Java OOP-class

    Naming a Pac k ageThe name of the class in the

    pac k age is rea lly

    The name of the class in the pac k age is rea lly

    Java grap hi cs. Rec t angle

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    88/104

    88

    Java OOP-class

    Access Modifiers(no k eyword): c lass/pac k age access (diffe r ent f r om C++ )

    I.e. , package available

    public : wor ld access (same as C++) private : class access (same as C++)

    protected : subclassing access(same as C++)

    static : on ly one copy for a ll instancesabstract : lef t unimp lemen tedfinal : no t overridden

    native : me thods imp lemen ted in na tive code.synchronized : descri bed in Threadtransient : da ta that is no t persis tent

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    89/104

    89

    Java OOP-class

    Comparisons

    Con trolling Access to Mem bers of a C lass

    Specifier Class Subclass Package Worldprivate Xprotected X X Xpublic X X X Xpackage X X

    X !

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    90/104

    90

    Java OOP class

    Staticstatic:

    only one copy for the c lass and a ll ins tancesUsually used as a g lo bal varia ble (even no ins tances)

    class TestStatic {int x, y, z;int average() { return (x+y+z)/3; }

    static int j = 0;static int peek() {

    j += 2;x = 3; // error!

    }static int k = peek();static { j = j*5; } // done when loading classpublic static void main(String[] args) {

    ...TestStatic ts = new TestStatic();int ave = ts.average();...

    }}

    S t ati c metho d

    S t ati c bl ock

    S t ati c var i able j, kS t ati c metho d

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    91/104

    91

    Java OOP class

    Fina lFina l varia bles:

    The va lue of a fina l varia ble canno t change af ter i t has beeninitialized.

    Such varia bles are simi lar to cons tants in o ther programminglang uages.

    final Color red = Color.red;

    A fina l loca l varia ble that has been dec lared but not yet ini tialized iscalled a blank fina l.

    final int blankfinal;. . .blankfinal = 0;

    Fina l methods: me thods that canno t be overridden.Preven t clients from overriding.Allow for JIT to op timize.

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    92/104

    92

    Java OOP class

    Transien t vs. Vo latiletransient : used in o bject seria liza tion to mar k mem ber varia bles that sho uld no t be seria lized.volatile : used to preven t the compi ler from

    performing cer tain op timiza tions on a mem ber.

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    93/104

    93

    Java OOP class

    Nes ted C lassA nes ted c lass is a c lass that is a mem ber of ano ther c lass.

    class Encl os ingClass{. . .class ANes t edClass {

    . . .}

    }Define a c lass wi thin ano ther c lass when the nes ted c lassmak es sense on ly in the con text of i ts enc losing c lass.

    For examp le, a text cursor ma k es sense on ly in the con text of a par ticular text componen t.

    A nes ted c lass has a specia l privi lege:It has unlimited access to i ts enc losing c lass's mem bers , even for

    priva te.Just lik e a me thod that can access priva te.

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    94/104

    94

    Types of Nes ted C lassclass Encl os ingClass{

    . . .s t ati c class AS t ati cNes t edClass {

    . . .}class Inn er Class {

    . . . / * s t ati c i s wr ong in thi s inn er class */}

    }

    A static nested class is called : a static nested class.A static nested class cannot r efe r di r ectly to instance va r iables o r m ethods defined in its enclosing class

    A nonstatic nested class is called an inne r class.An inne r class is associated with an instance of its enclosing class andhas di r ect access to that object's instance va r iables and m ethods.Because an inne r class is associated with an instance, it cannot defineany static m em be r s itself.

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    95/104

    95

    Nes ted vs. Inner To he l p differen tiate the terms nes ted c lass and inner c lass:

    The term "nes ted c lass" ref lects the syn tactic re lationship betweentwo c lasses.In con trast, the term "inner c lass" ref lects the re lationship betweenins tances of the two c lasses.

    An ins tance of InnerC lass can exis t only wi thin an ins tance of Enc losingC lass ,It has direc t access to ins tance varia bles and me thods of i ts enc losingins tance.

    class Encl os ingClass {

    . . .class Inn er Class {. . .

    }}

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    96/104

    96

    Examp le: Adap tor Using an Inner C lass to Imp lemen t an Adap ter

    impor t java. util.Enumera tion;impor t java. util.NoS uchE lemen tExcep tion;

    publ i c class S t ack {pr i vat e j ava.u ti l. Vec to r it ems;

    // ... code fo r S t ack's metho ds and cons t ruc to rs not s hown...

    publ i c Enumeration enumerato r () {re t ur n new S t ack Enum() ;

    }

    class S t ack Enum i mplement s Enumeration {int curre ntIt em = it ems.s iz e() - 1;publ i c boolea n h asMore Eleme nt s () {

    re t ur n ( curre ntIt em >= 0) ;}publ i c Obj ec t n extE leme nt() {if (!h asMore Element s())

    th r ow new NoS uchElementEx cep tion() ;else

    re t ur n it ems.eleme ntAt( curre ntIt em-- ) ;}

    }}

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    97/104

    97

    Anonymo us C lassY ou can decla r e an inne r class without na m ing it.E xa m ple : (Rew r ite the p r evious slide. )

    publ i c class S t ack {pr i vat e Vec to r it ems;...//c ode fo r S t ack's metho ds and cons t ruc to rs not s hown...publ i c Enumeration enumera to r () {

    re t ur n n ew Enumera tion() {int curre ntIt em = it ems.s iz e() - 1;publ i c boolea n h asMore Eleme nt s () {

    re t ur n ( curre ntIt em >= 0) ;}publ i c Obj ec t n extE leme nt() {

    if (!h asMore Eleme nt s ())th r ow new NoS uchEleme ntEx cep tion() ;

    else re t ur n it ems.eleme ntAt( curre ntIt em-- ) ;}

    };}

    }

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    98/104

    98

    U pcas ting and Po lymorphism(1/4) U pcas ting: Ta k ing an o bject reference and trea ting i t as areference to i ts base type is ca lled upcast ing , beca use of theway inheri tance trees are drawn wi th the base c lass a t the top.

    .

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    99/104

    99

    U pcas ting and Po lymorphism (2/4)Polymorphism : In Java , the princip le that the ac tual type of theo bject determines the me thod to be ca lled is ca lled polymorphism .

    class Shape {void draw( ) {}void erase( ) {}

    }

    class Circ le ex tends Shape {void draw( ) {

    Sys tem.o ut.prin tln("Circ le.draw( ) ");}void erase( ) {Sys tem.o ut.prin tln("Circ le.erase( )");}

    }

    Shape

    draw()erase()

    Squaredraw()erase()

    Triang ledraw()erase()

    Circ ledraw()erase()

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    100/104

    100

    class Sq uare ex tends Shape {void draw( ) {

    Sys tem.o ut.prin tln("Sq uare.draw( ) ");}

    void erase( ) {Sys tem.o ut.prin tln("Sq uare.erase( )");}}

    class Triang le ex tends Shape {void draw( ) {

    Sys tem.o ut.prin tln("Triang le.draw( )");}void erase( ) {Sys tem.o ut.prin tln("Triang le.erase( )");}

    }

    U pcas ting and Po lymorphism (3/4)

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    101/104

    101

    publ ic c lass Shapes { publ ic s tatic Shape randShape() {

    swi tch((in t) (Ma th.random()*3)) {case 0: return new Circ le();case 1: re turn new Sq uare();case 2: re turn new Triang le();defa ult : re turn new Circ le();}

    } publ ic s tatic void main(S tring[] args) {

    Shape[] s = new Shape[9];for (in t i = 0; i < s. leng th; i++)

    s[i] = randShape();//Ma k e po lymorphism me thod ca lls:

    for (in t i = 0; i < s. leng th; i++) s[i].d r aw( );}

    }

    U pcas ting and Po lymorphism (4/4)

    Java OOP-class

  • 8/8/2019 02 Java Oop Class

    102/104

    102

    Polymorphism in C++ (1/2)// polymo.cpp -- CopyWrong by [email protected]

    #include class Shape{

    public:virtual // run

    void draw( ) { cout

  • 8/8/2019 02 Java Oop Class

    103/104

    103

    Polymorphism in C++ (2/2)int main(){

    Circle * ppp;Shape * fig[9];

    // ppp = new Shape(); // errorppp = (Circle *)new Shape();ppp -> draw();ppp = (Circle *)new Line(); ppp -> draw();ppp = new Circle(); ppp -> draw();cout

  • 8/8/2019 02 Java Oop Class

    104/104

    J ava : OOP, Object, Class

    http://www.csie.nctu.edu.tw/~tsaiwn /course/ja v a/