clase 02- programacion orientada a objetos java ii

Upload: karlapalencia

Post on 02-Jun-2018

235 views

Category:

Documents


1 download

TRANSCRIPT

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    1/72

    1

    Creating Your OwnCreating Your Own

    ClassesClasses

    Sang ShinSang ShinMichle GarocheMichle Garoche

    www.javapassion.comwww.javapassion.com

    Learn with Passion!Learn with Passion!

    1

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    2/72

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    3/72

    3

    Defining YourDefining YourOwn ClassOwn Class

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    4/72

    4

    Defining your own classes

    Things to take note of for the snta! defined in thissection:

    " # or more occurrences of theline where it was applied to$

    %description& substitute an actual value forthis part instead of tping it as it is$

    ' this part is optional

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    5/72

    5

    Defining your own classes

    To define a class, we write:

    class {

    *

    *

    *

    } where

    %modifier& is an access modifier, which ma be combined withother tpes of modifier$

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    6/72

    6

    Example: Define StudentRecord

    Classpublic class StudentRecord{

    //we'll add more code here later

    }

    where, public means that our class is accessible to other classes

    outside the package

    class this is the keword used to create a class in *ava

    +tudentecord a uni-ue identifier that describes ourclass

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    7/72

    7

    Coding uidelines

    Think of an appropriate name for our class$ Don.t /ustcall our class 012 or an random names ou can thinkof$

    Class names starts with a CA34TA5 letter not are-uirement, however$

    The file name of our class must have the +A67 8A67as our class name$

    +tudentecord class should be defined in +tudentecord$/ava

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    8/72

    8

    Demo:Demo:

    Exercise !: Create your classExercise !: Create your class!"!#$javase$createclass%&ip!"!#$javase$createclass%&ip

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    9/72

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    10/72

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    11/72

    11

    Class (ariables

    ;or e!ample,

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    12/72

    12

    'nstance (ariables'nstance (ariables

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    13/72

    13

    Declaring *roperties ),ttributes+

    To declare a certain attribute for our class, we write,

    [

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    14/72

    14

    'nstance (ariables

    public class StudentRecord { // Instance variables

    pri"ateString name;pri"ateString address;pri"ateint age;pri"atedouble mathGrade;pri"atedouble englishGrade;pri"atedouble scienceGrade;pri"atedouble average;//we'll add more code here later

    }

    where,

    privatehere means that the variables are onl accessible withinthe class$

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    15/72

    15

    Coding uidelines for 'nstance(ariables

    Declare all our instance variables right after >publicclass 6class ?>

    Declare one variable for each line$

    4nstance variables, like an other variables should startwith a small letter$

    Use an appropriate data tpe for each variable oudeclare$ (mandator)

    Declare instance variables as private so that onlmethods in the same class can access them directl$

    7ncapsulation

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    16/72

    16

    Static (ariablesStatic (ariables

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    17/72

    17

    Static )Class+ variables

    public class StudentRecord {

    // static "ariables

    pri"ate staticint student%ount$

    // we'll add more code here later}

    we use the keword static to indicate that a variable is astatic (class) variable$

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    18/72

    18

    -et.ods-et.ods

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    19/72

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    20/72

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    21/72

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    22/72

    22

    Example /: ,ccessor )etter+ -et.od

    public class StudentRecord {

    pri"ate Strin) name$

    // some code

    // n e0ample in which the business lo)ic is

    // used to return a "alue on an accessor method

    public double )et"era)e({

    double result 1$

    resultmath2rade3en)lish2rade3science2rade(/4$return result$

    }

    }

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    23/72

    23

    -utator )Setter+ -et.ods

    6utator 6ethods

    used to write or change values of a variable

    Usuall written as:

    set

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    24/72

    24

    Example: -utator )Setter+ -et.od

    public class StudentRecord {

    private String name;

    :

    public "oid setame Strin) temp ({name = temp;

    }}

    where,

    public means that the method can be called from ob/ects ofother classes

    void means that the method does not return an value set8ame the name of the method

    (+tring temp) parameter that will be used inside our method

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    25/72

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    26/72

    26

    Example: -ultiple returnstatements

    public Strin) )etumber,n5ords int num ({

    Strin) defaultum 67ero6$

    if num 8 ({

    return 6one6$

    }

    else if num 9({

    return 6two6$

    }

    return defaultum$}

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    27/72

    27

    Static -et.odsStatic -et.ods

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    28/72

    28

    Static met.ods

    public class StudentRecord {

    pri"ate static int student%ount$public staticint )etStudent%ount({

    return student%ount$}

    }

    where, public means that the method can be called from ob/ects of

    other classes

    staticmeans that the method is static and should be called btping,'Class8ame$'method8ame$ ;or e!ample, in this case,we call the method StudentRecordgetStudent!ount"#

    int is the return tpe of the method$ This means that the methodshould return a value of tpe int

    get+tudentCount the name of the method

    () this means that our method does not have an parameters

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    29/72

    29

    Coding uidelines for -et.ods

    6ethod names should start with a small letter$

    6ethod names should sound like a verb

    3rovide documentation before the declaration of the

    method$ 1ou can use *avadocs stle for this$

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    30/72

    30

    0.en to Define Static -et.od1

    =hen the logic and state does not involve ob/ectinstances (different propert values of different ob/ectinstances do not pla a role in the logic)

    Computation method

    add(int !, int ) method

    =hen the logic is a convenience without creating anob/ect instance

    int mint @ 4nteger$parse4nt(>)E

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    31/72

    31

    Source Code for StudentRecordclass

    public class StudentRecord {

    // ,nstance "ariables

    pri"ate Strin) name$

    pri"ate Strin) address$

    pri"ate int a)e$

    pri"ate double math2rade$

    pri"ate double en)lish2rade$

    pri"ate double science2rade$

    pri"ate double a"era)e$

    pri"ate static int student%ount$

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    32/72

    32

    Source Code for StudentRecordClass

    /**

    * Returns the name of the student ccessor method(

    */

    public Strin) )etame({

    return name$

    }

    /**

    * %han)es the name of the student :utator method(*/

    public "oid setame Strin) temp ({

    name temp$

    }

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    33/72

    33

    Source Code for StudentRecord Class

    /**

    * %omputes the a"era)e of the en)lish; math and science

    * )rades ccessor method(

    */

    public double )et"era)e({

    double result 1$

    result math2rade3en)lish2rade3science2rade (/4$

    return result$

    }

    /**

    * returns the number of instances of StudentRecords

    * ccessor method(

    */

    public static int )etStudent%ount({

    return student%ount$

    }

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    34/72

    34

    Sample Source Code t.at usesStudentRecord Class

    public class StudentRecord$%ample{

    public static void main" String& args #{

    //create three ob(ects )or Student recordStudentRecord annaRecord = new StudentRecord"#;StudentRecord beahRecord = new StudentRecord"#;StudentRecord crisRecord = new StudentRecord"#;

    //set the name o) the studentsannaRecordset*ame"+,nna+#;beahRecordset*ame"+-eah+#;crisRecordset*ame"+!ris+#;

    //print anna's name

    S.stemoutprintln" annaRecordget*ame"# #;

    //print number o) studentsS.stemoutprintln"+!ount=+StudentRecordgetStudent!ount"##;}

    }

    static method

    instance method

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    35/72

    35

    *rogram Output

    nna

    Student %ount 1

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    36/72

    36

    Demo:Demo:

    Exercise /: Static2'nstance variables 3Exercise /: Static2'nstance variables 3Static2'nstance met.odsStatic2'nstance met.ods

    !"!#$javase$createclass%&ip!"!#$javase$createclass%&ip

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    37/72

    37

    OverloadingOverloading-et.ods-et.ods

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    38/72

    38

    -et.od Overloading

    6ethod overloading

    allows a method with the same name but differentparameters, to have different implementations and returnvalues of different tpes

    can be used when the same operation has differentimplementations$

    Alwas remember that overloaded methods have thefollowing properties:

    the same method name

    different number of parameters or different tpes ofparameters

    return tpes can be different or the same

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    39/72

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    40/72

    40

    Example

    public static void main" String&' args #{

    StudentRecord annaRecord = new StudentRecord"#;

    annaRecordset*ame"+,nna+#;annaRecordset,ddress"+1hilippines+#;

    annaRecordset,ge"23#;annaRecordset0athGrade"45#;

    annaRecordset$nglishGrade"633#;annaRecordsetScienceGrade"255#;

    //overloaded methodsannaRecordprint" annaRecordget*ame"# #;annaRecordprint" annaRecordget$nglishGrade"#7

    annaRecordget0athGrade"#7 annaRecordgetScienceGrade"##;

    }

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    41/72

    41

    Output

    we will have the output for the first call to print,

    ame.nna

    ddress.hilippines

    )e.8=

    we will have the output for the second call to print,

    ame.nna

    :ath 2rade.1?1

    @n)lish 2rade.A=?=

    Science 2rade.811?1

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    42/72

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    43/72

    43

    ConstructorsConstructors

    )Constructor)Constructor-et.ods+-et.ods+

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    44/72

    44

    Constructors

    Constructors are important in instantiating an ob/ect$ 4tis a method where all the initialiFations are placed$

    The following are the properties of a constructor:

    Constructors have the same name as the class

    A constructor is /ust like an ordinar method with some differences

    Constructors does not have an return value

    1ou cannot call a constructor directl, it gets called indirectl when

    ob/ect gets instantiated

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    45/72

    45

    Constructors

    To declare a constructor, we write,

    *( {

    *

    }

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    46/72

    46

    Default Constructor )-et.od+

    The default constructor )no5arg constructor+

    is the constructor without an parameters$

    4f the class does not specif an constructors, then andefault constructor gets created automaticall b thecompiler

    4f there is alread a constructor, then default constructordoes not get created automaticall b the compiler

    E l D f lt C t t

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    47/72

    47

    Example: Default Constructor-et.od of StudentRecord Class// Default constructor of StudentRecord class

    public StudentRecord({

    //some code here

    }

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    48/72

    48

    Overloading Constructor -et.odspublic StudentRecord({

    //some initiali7ation code here

    }

    public StudentRecordStrin) temp({

    this?name temp$

    }

    public StudentRecordStrin) name; Strin) address({

    this?name name$

    this?address address$

    }

    public StudentRecorddouble m2rade; double e2rade;double s2rade({

    math2rade m2rade$

    en)lish2rade e2rade$

    science2rade s2rade$

    }

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    49/72

    49

    Example: 6sing Constructors

    public static "oid main Strin)[# ar)s ({

    //create three obBects for Student record

    StudentRecord annaRecord

    new StudentRecord6nna6($

    StudentRecord beahRecord

    new StudentRecord6Ceah6;

    6hilippines6($

    StudentRecord crisRecord

    new StudentRecord1;A1;811($

    //some code here

    }

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    50/72

    50

    7t.is)+8 constructor call

    Constructor calls can be chained, meaning, ou cancall another constructor from inside anotherconstructor$

    =e use the this()call for this

    There are a few things to remember when using thethis()constructor call:

    =hen using the this constructor call, 4T 6U+T

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    51/72

    51

    Example

    2: public StudentRecord"#{8: this"+some string+#;9:: }3:: public StudentRecord"String temp#{

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    52/72

    52

    Demo:Demo:

    Exercise #: ConstructorExercise #: Constructor!"!#$javase$createclass%&ip!"!#$javase$createclass%&ip

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    53/72

    53

    77t.is8 Referencet.is8 Reference

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    54/72

    54

    7t.is8 reference

    The thisreference

    refers to current ob/ect instance itself

    used to access the instance variables

    To use the this reference, we tpe,

    this?

    1ou can onl use the this reference for instance variablesand 8

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    55/72

    55

    7t.is8 reference

    The thisreference is assumed when ou call a methodfrom the same ob/ect

    public class 6Class ?

    void a6ethod() ?

    BB same thing as this$another6ethod()

    another6ethod()E

    H

    void another6ethod() ?

    BB method definition here$$$

    H

    H

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    56/72

    56

    Example

    public "oid set)e int a)e ({

    this?a)e a)e$

    }

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    57/72

    57

    Demo:Demo:

    Exercise 9: 7t.is8Exercise 9: 7t.is8!"!#$javase$createclass%&ip!"!#$javase$createclass%&ip

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    58/72

    58

    ,ccess -odifiers,ccess -odifiers

    , - difi

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    59/72

    59

    ,ccess -odifiers

    There are four different tpes of member accessmodifiers in *ava:

    public (5east restrictive)

    protected

    default

    private (6ost restrictive)

    The three access modifiers in blue color are e!plicitl

    written in the code to indicate the access tpe, for theIrd one (>default), no keword is used$

    bli ibilit

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    60/72

    60

    public accessibility

    publicaccess

    specifies that class members (variables or methods) areaccessible to anone, both inside and outside the classand outside of the package to which the class belongs

    An ob/ect that interacts with the class can have accessto the public members of the class$

    Jeword: public

    E l 7 bli 8 , - dif

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    61/72

    61

    Example: 7public8 ,ccess -odifer

    public class StudentRecord {

    // public access to instance "ariable

    publicint name$

    // public access to method

    publicStrin) )etame({

    return name$

    }

    }

    t t d ibilit

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    62/72

    62

    protected accessibility

    protectedaccess

    +pecifies that the class members are accessible onl tomethods in that class and the subclasses of the class$

    The subclass can be in different packages

    Jeword: protected

    E l 7 t t d8 , - difi

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    63/72

    63

    Example: 7protected8 ,ccess -odifier

    public class StudentRecord {

    //protected access to instance "ariable

    protectedStrin) name$

    //protected access to method

    protectedStrin) )etame({

    return name$

    }

    }

    default accessibility

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    64/72

    64

    default accessibility

    Default access

    specifies that onl classes in the same package can haveaccess to the class. variables and methods

    no actual keword for the default modifierE it is applied in

    the absence of an access modifier$

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    65/72

    private accessibility

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    66/72

    66

    private accessibility

    privateaccessibilit

    specifies that the class members are onl accessiblewithin the class

    Jeword: private

    Example: 7private8 ,ccess -odifier

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    67/72

    67

    Example: private ,ccess -odifier

    public class StudentRecord {

    //pri"ate access to instance "ariable

    pri"ateint name$

    //pri"ate access to method

    pri"ateStrin) )etame({

    return name$

    }

    }

    ava *rogram Structure:;. , - difi

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    68/72

    68

    ;.e ,ccess -odifiers

    Coding uidelines

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    69/72

    69

    Coding uidelines

    The instance variables of a class should normall bedeclared private, and the class will /ust provideaccessor and mutator methods to these variables$

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    70/72

    70

    Demo:Demo:

    Exercise

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    71/72

    71

    Summary

    Defining our own classes Declaring ;ields (instance, staticBclass)

    Declaring 6ethods (accessor, mutator, static)

    eturning values and 6ultiple return statements

    The this reference

    6ethod overloading

    Constructors (default, overloading, this() call)

    3ackages Access 6odifiers (default, public, private, protected)

  • 8/10/2019 Clase 02- Programacion Orientada a Objetos Java II

    72/72

    72

    ;.an= you>;.an= you>

    Check JavaPassion.com Coecamps!Check JavaPassion.com Coecamps!

    http""www.javapassion.com"coecampshttp""www.javapassion.com"coecampsLearn with Passion!Learn with Passion!

    72

    http://www.javapassion.com/codecampshttp://www.javapassion.com/codecampshttp://www.javapassion.com/codecamps