programming

Upload: noreenatis

Post on 07-Jan-2016

215 views

Category:

Documents


0 download

DESCRIPTION

sample

TRANSCRIPT

  • 7/17/2019 programming

    1/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.1

    Chapter 9 Objects and Classes

  • 7/17/2019 programming

    2/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.2

    Motivations

    After learning the preceding chapters, you are capable of

    solving many programming problems using selections,loops, methods, and arrays. o!ever, these "ava features

    are not sufficient for developing graphical user interfaces

    and large scale soft!are systems. #uppose you !ant to

    develop a graphical user interface as sho!n belo!. o! doyou program it$

  • 7/17/2019 programming

    3/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.%

    Objectives &o describe objects and classes, and use classes to model objects '(9.2).

    &o use *M+ graphical notation to describe classes and objects '(9.2).

    &o demonstrate ho! to define classes and create objects '(9.%). &o create objects using constructors '(9.).

    &o access objects via object reference variables '(9.-).

    &o define a reference variable using a reference type '(9.-.1).

    &o access an objects data and methods using the object member access operator '.) '(9.-.2).

    &o define data fields of reference types and assign default values for an objects data fields '(9.-.%).

    &o distinguish bet!een object reference variables and primitive data type variables '(9.-.).

    &o use the "ava library classes Date, Random, and Point2D'(9./).

    &o distinguish bet!een instance and static variables and methods '(9.0).

    &o define private data fields !ith appropriategetand setmethods '(9.).

    &o encapsulate data fields to mae classes easy to maintain '(9.9).

    &o develop methods !ith object arguments and differentiate bet!een primitive3type arguments andobject3type arguments '(9.14).

    &o store and process objects in arrays '(9.11).

    &o create immutable objects from immutable classes to protect the contents of objects '(9.12).

    &o determine the scope of variables in the conte5t of a class '(9.1%).

    &o use the ey!ord thisto refer to the calling object itself '(9.1).

  • 7/17/2019 programming

    4/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.

    OO 6rogramming Concepts

    Object3oriented programming 'OO6) involves

    programming using objects. An objectrepresentsan entity in the real !orld that can be distinctly

    identified. 7or e5ample, a student, a des, a circle,

    a button, and even a loan can all be vie!ed asobjects. An object has a uni8ue identity, state, and

    behaviors. &hestateof an object consists of a set of

    datafields'also no!n asproperties) !ith theircurrent values. &he behaviorof an object is defined

    by a set of methods.

  • 7/17/2019 programming

    5/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.-

    Objects

    An object has both a state and behavior. &he state

    defines the object, and the behavior defines !hat

    the object does.

    Class ame: Circle

    ;ata 7ields:radius is

  • 7/17/2019 programming

    6/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved./

    Classes

    Classesare constructs that define objects of thesame type. A "ava class uses variables to define

    data fields and methods to define behaviors.

    Additionally, a class provides a special type ofmethods, no!n as constructors, !hich are

    invoed to construct objects from the class.

  • 7/17/2019 programming

    7/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.0

    Classes

    class Circle {

    /** The radius of this circle */double radius = 1.0;

    /** Construct a circle object */

    Circle() {

    }

    /** Construct a circle object */

    Circle(double newadius) {

    radius = newadius;

    }

    /** eturn the area of this circle */double !et"rea() {

    return radius * radius * #.1$1%&;

    }

    }

    'ata field

    ethod

    Constructors

  • 7/17/2019 programming

    8/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.

    *M+ Class ;iagram

    Circle

    radius: double

    Circle')

    Circle'ne!=adius: double)

    getArea'): double

    circle1: Circle

    radius > 1.4

    Class name

    ;ata fields

    Constructors and

    methods

    circle2: Circle

    radius > 2-

    circle%: Circle

    radius > 12-

    *M+ Class ;iagram

    *M+ notation

    for objects

  • 7/17/2019 programming

    9/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.9

    Example: Defning Classes

    and Creating Objects

    Objective: ;emonstrate creating objects,

    accessing data, and using methods.

    TestSimpleCircleTestSimpleCircle RunRun

    Animation

    http://var/www/apps/conversion/tmp/scratch_1/html%2FTestSimpleCircle.bathttp://var/www/apps/conversion/tmp/scratch_1/html%2FTestSimpleCircle.bathttp://var/www/apps/conversion/tmp/scratch_1/html%2FTestSimpleCircle.bat
  • 7/17/2019 programming

    10/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.14

    Example: Defning Classes and CreatingObjects

    TestTVTestTV RunRun

    TVTV

    TV

    channel int

    *olu+e,e*el int

    on boolean

    -T.()

    -turn/n() *oid

    -turn/ff() *oid

    -setChannel(newChannel int) *oid

    -set.olu+e(new.olu+e,e*el int) *oid

    -channel01() *oid

    -channel'own() *oid

    -*olu+e01() *oid

    -*olu+e'own() *oid

    &he current channel '1 to 124) of this &?.

    &he current volume level '1 to 0) of this &?.

    @ndicates !hether this &? is onAoff.

    Constructs a default &? object.

    &urns on this &?.

    &urns off this &?.

    #ets a ne! channel for this &?.#ets a ne! volume level for this &?.

    @ncreases the channel number by 1.

    ;ecreases the channel number by 1.

    @ncreases the volume level by 1.

    ;ecreases the volume level by 1.

    &he B sign indicatesa public modifier.

    http://var/www/apps/conversion/tmp/scratch_1/html%2FTestTV.bathttp://var/www/apps/conversion/tmp/scratch_1/html%2FTestTV.bathttp://var/www/apps/conversion/tmp/scratch_1/html%2FTestTV.bat
  • 7/17/2019 programming

    11/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.11

    Constructors

    Circle() {

    }

    Circle(double newRadius) {

    radius = newRadius;

    }

    Constructors are a specialind of methods that are

    invoed to construct objects.

  • 7/17/2019 programming

    12/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.12

    Constructors, cont.

    A constructor !ith no parameters is referred to as ano-arg constructor.

    Constructors must have the same name as the

    class itself.

    Constructors do not have a return typeDnot

    even void.

    Constructors are invoed using the ne!

    operator !hen an object is created. Constructors

    play the role of initialiEing objects.

  • 7/17/2019 programming

    13/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.1%

    Creating Objects *sing

    Constructors

    new ClassName();

    F5ample:new Circle();

    new Circle(5.0);

  • 7/17/2019 programming

    14/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.1

    ;efault Constructor

    A class may be defined !ithout constructors. @nthis case, a no3arg constructor !ith an empty body

    is implicitly defined in the class. &his constructor,

    called a default constructor, is providedautomatically only if no constructors are explicitly

    defined in the class.

  • 7/17/2019 programming

    15/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.1-

    ;eclaring Object =eference ?ariables

    &o reference an object, assign the object to a referencevariable.

    &o declare a reference variable, use the synta5:

    ClassName objectRefVar;

    F5ample:

    Circle mCircle;

  • 7/17/2019 programming

    16/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.1/

    ;eclaringCreating Objects

    in a #ingle #tepClass2a+e objectefar= new Class2a+e();

    F5ample:

    Circle +3Circle = new Circle();

    Create an objectAssign object reference

  • 7/17/2019 programming

    17/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.10

    Accessing Objects Members

    =eferencing the objects data: objectefar.data

    e.g., +3Circle.radius

    @nvoing the objects method:

    objectefar.+ethod2a+e(ar!u+ents)

    e.g., +3Circle.!et"rea()

    i ti

  • 7/17/2019 programming

    18/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.1

    &race Code

    Circle myCircle = new Circle(5.0);

    Circle yorCircle = new Circle();

    yorCircle.radis = !00;

    ;eclare myCircle

    no valuemyCircle

    animation

    i ti

  • 7/17/2019 programming

    19/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.19

    &race Code, cont.

    Circle myCircle = new Circle(5.0);

    Circle yorCircle = new Circle();

    yorCircle.radis = !00;

    : Circle

    radius: -.4

    no valuemyCircle

    Create a circle

    animation

    i ti

  • 7/17/2019 programming

    20/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.24

    &race Code, cont.

    Circle myCircle = new Circle(5.0);

    Circle yorCircle = new Circle();

    yorCircle.radis = !00;

    : Circle

    radius: -.4

    reference valuemyCircle

    Assign objectreference to myCircle

    animation

    animation

  • 7/17/2019 programming

    21/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.21

    &race Code, cont.

    Circle myCircle = new Circle(5.0);

    Circle yorCircle = new Circle();

    yorCircle.radis = !00;

    : Circle

    radius: -.4

    reference valuemyCircle

    no valueyourCircle

    ;eclare yourCircle

    animation

    animation

  • 7/17/2019 programming

    22/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.22

    &race Code, cont.

    Circle myCircle = new Circle(5.0);

    Circle yorCircle = new Circle();

    yorCircle.radis = !00;

    : Circle

    radius: -.4

    reference valuemyCircle

    no valueyourCircle

    : Circle

    radius: 1.4Create a ne!

    Circle object

    animation

    animation

  • 7/17/2019 programming

    23/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.2%

    &race Code, cont.

    Circle myCircle = new Circle(5.0);

    Circle yorCircle = new Circle();

    yorCircle.radis = !00;

    : Circle

    radius: -.4

    re"erence #alemyCircle

    re"erence #aleyourCircle

    : Circle

    radius: 1.4

    Assign object

    reference to yourCircle

    animation

    animation

  • 7/17/2019 programming

    24/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.2

    &race Code, cont.

    Circle myCircle = new Circle(5.0);

    Circle yorCircle = new Circle();

    yorCircle.radis = !00;

    : Circle

    radius: -.4

    reference valuemyCircle

    reference valueyourCircle

    : Circle

    radius: 144.4Change radius in

    yourCircle

    animation

  • 7/17/2019 programming

    25/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.2-

    Caution

    =ecall that you use

    Math.methodame'arguments) 'e.g., Math.po!'%, 2.-))

    to invoe a method in the Math class. Can you invoe getArea') using#impleCircle.getArea')$ &he ans!er is no. All the methods used before

    this chapter are static methods, !hich are defined using the staticey!ord. o!ever, getArea') is non3static. @t must be invoed from anobject using

    object=ef?ar.methodame'arguments) 'e.g., myCircle.getArea')).

    More e5planations !ill be given in the section on G#tatic ?ariables,Constants, and Methods.H

  • 7/17/2019 programming

    26/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.2/

    =eference ;ata 7ields

    &he data fields can be of reference types. 7or e5ample,

    the follo!ing #tudent class contains a data field name ofthe #tring type.

    !ublic class "tudent {

    "trin# name; $$ name %as default &alue null

    int a#e; $$ a#e %as default &alue 0

    boolean is"cience'ajor; $$ is"cience'ajor %as default &alue false

    c%ar #ender; $$ c %as default &alue u0000

    }

  • 7/17/2019 programming

    27/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.20

    &he null ?alue

    @f a data field of a reference type does notreference any object, the data field holds a

    special literal value, null.

  • 7/17/2019 programming

    28/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.2

    ;efault ?alue for a ;ata 7ield

    &he default value of a data field is null for a referencetype, 4 for a numeric type, false for a boolean type,and IJu4444I for a char type. o!ever, "ava assignsno default value to a local variable inside a method.

    !ublic class *est {

    !ublic static &oid main("trin#+, ar#s) {

    "tudent student = new "tudent();

    "stem.out.!rintln(-name - / student.name);

    "stem.out.!rintln(-a#e - / student.a#e);

    "stem.out.!rintln(-is"cience'ajor - / student.is"cience'ajor);

    "stem.out.!rintln(-#ender - / student.#ender);

    }

    }

  • 7/17/2019 programming

    29/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.29

    F5ample

    !ublic class *est {

    !ublic static &oid main("trin#+, ar#s) {

    int ; $$ %as no default &alue "trin# ; $$ %as no default &alue

    "stem.out.!rintln(- is - / );

    "stem.out.!rintln(- is - / );

    }

    }

    Compile error: variable not

    initialiEed

    "ava assigns no default value to a local variable inside a method.

    ;iff b t ? i bl f

  • 7/17/2019 programming

    30/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.%4

    ;ifferences bet!een ?ariables of

    6rimitive ;ata &ypes and Object &ypes

    16rimitive type int i > 1 i

    Object type Circle c c reference

    Created using ne! Circle')

    c: Circle

    radius > 1

    C i ? i bl f 6 i i i

  • 7/17/2019 programming

    31/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.%1

    Copying ?ariables of 6rimitive

    ;ata &ypes and Object &ypes

    i

    6rimitive type assignment i > j

    Kefore:

    1

    j 2

    i

    After:

    2

    j 2

    c1

    Object type assignment c1 > c2

    Kefore:

    c2

    c1

    After:

    c2

    c1: Circle

    radius > -

    C2: Circle

    radius > 9

    c1: Circle

    radius > -

    C2: Circle

    radius > 9

  • 7/17/2019 programming

    32/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.%2

    Larbage Collection

    As sho!n in the previous figure, after theassignment statement c1 > c2, c1 points to

    the same object referenced by c2. &he object

    previously referenced by c1 is no longerreferenced. &his object is no!n as garbage.

    Larbage is automatically collected by "?M.

  • 7/17/2019 programming

    33/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.%%

    Larbage Collection, cont

    &@6: @f you no! that an object is no longerneeded, you can e5plicitly assign null to a

    reference variable for the object. &he "?M

    !ill automatically collect the space if theobject is not referenced by any variable.

  • 7/17/2019 programming

    34/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.%

    &he ;ate Class

    "ava provides a system3independent encapsulation of date

    and time in the java.util.;ate class. ou can use the ;ateclass to create an instance for the current date and time anduse its to#tring method to return the date and time as a string.

    java.util.;ate

    B;ate')

    B;ate'elapse&ime: long)

    Bto#tring'): #tring

    Bget&ime'): long

    Bset&ime'elapse&ime: long): void

    Constructs a ;ate object for the current time.

    Constructs a ;ate object for a given time in

    milliseconds elapsed since "anuary 1, 1904, LM&.

    =eturns a string representing the date and time.

    =eturns the number of milliseconds since "anuary 1,

    1904, LM&.

    #ets a ne! elapse time in the object.

    &he B sign indicates

    public modifer

  • 7/17/2019 programming

    35/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.%-

    &he ;ate Class F5ample

    7or e5ample, the follo!ing code

    jaa.util.'ate date = new jaa.util.'ate();

    43ste+.out.rintln(date.to4trin!());

    displays a string lie4un ar 0& 1#%01&

    54T 600#.

  • 7/17/2019 programming

    36/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.%/

    &he =andom Class

    ou have used Math.random') to obtain a random double

    value bet!een 4.4 and 1.4 'e5cluding 1.4). A more usefulrandom number generator is provided in the java.util.=andomclass.

    java.util.=andomB=andom')

    B=andom'seed: long)

    Bne5t@nt'): int

    Bne5t@nt'n: int): int

    Bne5t+ong'): long

    Bne5t;ouble'): double

    Bne5t7loat'): float

    Bne5tKoolean'): boolean

    Constructs a =andom object !ith the current time as its seed.

    Constructs a =andom object !ith a specified seed.

    =eturns a random int value.

    =eturns a random int value bet!een 4 and n 'e5clusive).

    =eturns a random long value.

    =eturns a random double value bet!een 4.4 and 1.4 'e5clusive).

    =eturns a random float value bet!een 4.47 and 1.47 'e5clusive).

    =eturns a random boolean value.

  • 7/17/2019 programming

    37/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.%0

    &he =andom Class F5ample@f t!o =andom objects have the same seed, they !ill generate

    identical se8uences of numbers. 7or e5ample, the follo!ing codecreates t!o =andom objects !ith the same seed %.

    Random random1 = new Random(2);

    "stem.out.!rint(-3rom random14 -);

    for (int i = 0; i 10; i//) "stem.out.!rint(random1.net6nt(1000) / - -);

    Random random7 = new Random(2);

    "stem.out.!rint(-n3rom random74 -);

    for (int i = 0; i 10; i//)

    "stem.out.!rint(random7.net6nt(1000) / - -);

    7rom random1: 0% //4 214 -1 12 242 -9 -/ -9 9/1

    7rom random2: 0% //4 214 -1 12 242 -9 -/ -9 9/1

  • 7/17/2019 programming

    38/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.%

    &he Point2DClass

    "ava A6@ has a conveninent Point2Dclass in the

    $a#a"%.geometrypacage for representing a point in a t!o3dimensional plane.

    PointDPointD RunRun

    @ t

    http://var/www/apps/conversion/tmp/scratch_1/html%2FTestPoint2D.bathttp://var/www/apps/conversion/tmp/scratch_1/html%2FTestPoint2D.bathttp://var/www/apps/conversion/tmp/scratch_1/html%2FTestPoint2D.bat
  • 7/17/2019 programming

    39/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.%9

    @nstance

    ?ariables, and Methods

    @nstance variables belong to a specific instance.

    @nstance methods are invoed by an instance of

    the class.

    #t ti ? i bl C t t

  • 7/17/2019 programming

    40/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.4

    #tatic ?ariables, Constants,

    and Methods

    #tatic variables are shared by all the instances of the

    class.

    #tatic methods are not tied to a specific object.

    #tatic constants are final variables shared by all the

    instances of the class.

    #t ti ? i bl C t t

  • 7/17/2019 programming

    41/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.1

    #tatic ?ariables, Constants,

    and Methods, cont.

    &o declare static variables, constants, and methods,

    use the static modifier.

    #t ti ? i bl C t t

  • 7/17/2019 programming

    42/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.2

    #tatic ?ariables, Constants,

    and Methods, cont.

    F5ample of

  • 7/17/2019 programming

    43/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.%

    F5ample of

    *sing @nstance and Class ?ariables

    and Method

    Objective: ;emonstrate the roles of

    instance and class variables and theiruses. &his e5ample adds a class variablenumberOfObjects to trac the number ofCircle objects created.

    TestCircle!it"Static#embersTestCircle!it"Static#embers RunRun

    Circle!it"Static#embersCircle!it"Static#embers

    ?isibility Modifiers and

    http://var/www/apps/conversion/tmp/scratch_1/html%2FTestCircleWithStaticMembers.bathttp://var/www/apps/conversion/tmp/scratch_1/html%2FTestCircleWithStaticMembers.bathttp://var/www/apps/conversion/tmp/scratch_1/html%2FTestCircleWithStaticMembers.bat
  • 7/17/2019 programming

    44/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.

    ?isibility Modifiers and

    AccessorMutator Methods

    Ky default, the class, variable, or method can beaccessed by any class in the same pacage.

    ublic

    &he class, data, or method is visible to any class in anypacage.

    riate

    &he data or methods can be accessed only by the declaringclass.

    &he get and set methods are used to read and modify private

    properties.

  • 7/17/2019 programming

    45/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.-

    &he private modifier restricts access to !ithin a class, the default

    modifier restricts access to !ithin a pacage, and the public

    modifier enables unrestricted access.

  • 7/17/2019 programming

    46/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved./

    O&F

    An object cannot access its private members, as sho!n in 'b).@t is ON, ho!ever, if the object is declared in its o!n class, as

    sho!n in 'a).

    hy ;ata 7ields #hould Ke

  • 7/17/2019 programming

    47/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.0

    hy ;ata 7ields #hould Ke

    private$

    &o protect data.

    &o mae code easy to maintain.

    F ample of

  • 7/17/2019 programming

    48/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.

    F5ample of

    ;ata 7ield Fncapsulation

    Circle!it"Pri$ateData%ieldsCircle!it"Pri$ateData%ields

    RunRunTestCircle!it"Pri$ateData%ieldsTestCircle!it"Pri$ateData%ields

    Circle

    3radius: double

    3numberOfObjects: int

    BCircle')

    BCircle'radius: double)

    Bget=adius'): double

    Bset=adius'radius: double): void

    BgetumberOfObjects'): int

    BgetArea'): double

    &he radius of this circle 'default: 1.4).

    &he number of circle objects created.

    Constructs a default circle object.

    Constructs a circle object !ith the specified radius.

    =eturns the radius of this circle.

    #ets a ne! radius for this circle.

    =eturns the number of circle objects created.

    =eturns the area of this circle.

    &he 3 sign indicates

    private modifier

    http://var/www/apps/conversion/tmp/scratch_1/html%2FTestCircleWithPrivateDataFields.bathttp://var/www/apps/conversion/tmp/scratch_1/html%2FTestCircleWithPrivateDataFields.bathttp://var/www/apps/conversion/tmp/scratch_1/html%2FTestCircleWithPrivateDataFields.bat
  • 7/17/2019 programming

    49/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.9

    6assing Objects to Methods

    6assing by value for primitive type value

    'the value is passed to the parameter)

    6assing by value for reference type value'the value is the reference to the object)

    TestPassObjectTestPassObject RunRun

    6 i Obj M h d

    http://var/www/apps/conversion/tmp/scratch_1/html%2FTestPassObject.bathttp://var/www/apps/conversion/tmp/scratch_1/html%2FTestPassObject.bathttp://var/www/apps/conversion/tmp/scratch_1/html%2FTestPassObject.bat
  • 7/17/2019 programming

    50/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.-4

    6assing Objects to Methods, cont.

  • 7/17/2019 programming

    51/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.-1

    Array of Objects

    Circle78 circle"rra3 = new Circle7108;

    An array of objects is actually an array of

    reference variables. #o invoingcircleArrayP1Q.getArea') involves t!olevels of referencing as sho!n in the ne5t

    figure. circleArray references to the entirearray. circleArrayP1Q references to aCircle object.

  • 7/17/2019 programming

    52/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. A

    rights reserved.-2

    Array of Objects, cont.

    Circle78 circle"rra3 = new Circle7108;

  • 7/17/2019 programming

    53/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Arights reserved.

    -%

    Array of Objects, cont.

    #ummariEing the areas of the circles

    TotalAreaTotalArea RunRun

    @ bl Obj d Cl

    http://var/www/apps/conversion/tmp/scratch_1/html%2FTotalArea.bathttp://var/www/apps/conversion/tmp/scratch_1/html%2FTotalArea.bathttp://var/www/apps/conversion/tmp/scratch_1/html%2FTotalArea.bat
  • 7/17/2019 programming

    54/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Arights reserved.

    -

    @mmutable Objects and Classes

    @f the contents of an object cannot be changed once the object is

    created, the object is called an immutable objectand its class is

    called an immutable class. @f you delete the set method in the

    Circle class in +isting .14, the class !ould be immutable because

    radius is private and cannot be changed !ithout a set method.

    A class !ith all private data fields and !ithout mutators is not

    necessarily immutable. 7or e5ample, the follo!ing class #tudent

    has all private data fields and no mutators, but it is mutable.

    F5ample bli l 8i t%9 t {

  • 7/17/2019 programming

    55/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Arights reserved.

    --

    F5ample!ublic class "tudent {

    !ri&ate int id;

    !ri&ate 8irt%9ate birt%9ate;

    !ublic "tudent(int ssn:

    int ear: int mont%: int da) {

    id = ssn;

    birt%9ate = new 8irt%9ate(ear: mont%: da);

    }

    !ublic int #et6d() {

    return id;

    }

    !ublic 8irt%9ate #et8irt%9ate() {

    return birt%9ate;

    }

    }

    !ublic class 8irt%9ate {

    !ri&ate int ear;

    !ri&ate int mont%;

    !ri&ate int da;

    !ublic 8irt%9ate(int newear:int new'ont%: int new9a) {

    ear = newear;

    mont% = new'ont%;

    da = new9a;

    }

    !ublic &oid setear(int newear) { ear = newear;

    }

    }

    !ublic class *est {

    !ublic static &oid main("trin#+, ar#s) { "tudent student = new "tudent(111772222: 1

    }

    }

    h Cl i @ bl $

  • 7/17/2019 programming

    56/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Arights reserved.

    -/

    hat Class is @mmutable$

    7or a class to be immutable, it must mar all data fields privateand provide no mutator methods and no accessor methods that

    !ould return a reference to a mutable data field object.

  • 7/17/2019 programming

    57/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Arights reserved.

    -0

    #cope of ?ariables

    &he scope of instance and static variables is the

    entire class. &hey can be declared any!here inside

    a class.

    &he scope of a local variable starts from its

    declaration and continues to the end of the bloc

    that contains the variable. A local variable must be

    initialiEed e5plicitly before it can be used.

  • 7/17/2019 programming

    58/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Arights reserved.

    -

    &he this Ney!ord

    &he this ey!ord is the name of a reference thatrefers to an object itself. One common use of the

    this ey!ord is reference a classs hidden data

    fields.

    Another common use of the this ey!ord to

    enable a constructor to invoe another

    constructor of the same class.

  • 7/17/2019 programming

    59/60

    Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Arights reserved.

    -9

    =eference the idden ;ata 7ields

    !ublic class9 {!ri&ate inti = %;

    !ri&ate static double: = 0;

    &oidset(inti) {

    this.i = i;

    }

    static &oidset where thisrefers f1

    n*o:in! f6.set($%) is to eecute

    t%is.i = $%> where thisrefers f6

    C lli O l d d C

  • 7/17/2019 programming

    60/60

    Calling Overloaded Constructor

    ublic class Circle {riate double radius;

    ublic Circle(double radius) {

    t%is.radius = radius;

    }

    ublic Circle() {

    t%is(1.0);

    }

    ublic double !et"rea() {return t%is.radius * t%is.radius * ath.?;

    }

    } Fvery instance variable belongs to an instance represented by this,!hich is normally omitted

    this must be e5plicitly used to reference the data

    field radius of the object being constructed

    this is used to invoe another constructor