610 Chapter 02

download 610 Chapter 02

of 43

Transcript of 610 Chapter 02

  • 8/11/2019 610 Chapter 02

    1/43

    Comprensin de las

    definiciones de clase

    Mirando dentro de las clases

    5.0

  • 8/11/2019 610 Chapter 02

    2/43

    2

    Conceptos principales a

    tratarse campos

    constructores

    mtodos parmetros

    instrucciones de asignacin

  • 8/11/2019 610 Chapter 02

    3/43

    3

    Mquinas de entradas - una

    visin externa Explorando el comportamiento de una mquinatpica de entradas.

    Utilice el proyecto ingenuo-ticket-mquina.

    Mquinas suministran entradas de un precio fijo. Cmo se determina ese precio?

    Cmo es el "dinero" dentr en una mquina?

    Cmo una mquina de hacer un seguimientodel dinero que se ingresa?

  • 8/11/2019 610 Chapter 02

    4/43

    4

    Las mquinas del boleto

    demostracin

  • 8/11/2019 610 Chapter 02

    5/43

    5

    Mquinas de entradas - una

    vista interna La interaccin con un objeto nos da

    pistas sobre su comportamiento.

    Mirando el interior nos permitedeterminar cmo se proporciona oimplement ese comportamiento.

    Todas las clases de Java tienen unavisin interna de aspecto similar.

  • 8/11/2019 610 Chapter 02

    6/43

    6

    Estructura de clases bsica

    public class TicketMachine

    {

    Parte interna omitirse.

    }

    public class ClassName

    {

    Los campos

    Constructores

    Mtodos

    }

    La capa exterior deTicketMachine

    El contenido

    interno de unaclase

  • 8/11/2019 610 Chapter 02

    7/43

    7

    Palabras clave

    Palabras con un significado especialen el lenguaje:

    pblica clase

    privado

    int Tambin conocido como palabras

    reservadas.

  • 8/11/2019 610 Chapter 02

    8/43

    8

    Los campos Los campos almacenan

    los valores de un objeto. Tambin son conocidos

    como variables deinstancia.

    Los campos definen elestado de un objeto. Utilice Inspeccione para

    ver el estado. Algunos valores cambian

    a menudo. Algunos cambios rara vez

    (o nunca).

    public class TicketMachine{

    private int price;

    private int balance;

    private int total;

    Further details omitted.

    }

    private int price;

    visibility modifier type variable name

  • 8/11/2019 610 Chapter 02

    9/43

    9

    Constructores

    Inicialice un objeto.

    Tener el mismo nombre que su clase.

    Estrecha asociacin con los campos.

    Guarde los valores iniciales en los campos. Valores de los parmetros externos de este.

    public TicketMachine(int cost){

    price = cost;

    balance = 0;

    total = 0;

    }

  • 8/11/2019 610 Chapter 02

    10/43

    10

    Passing data via parameters

    Los parmetros son otro

    tipo de variable. Los

    parmetros son otro

    tipo de variable.

  • 8/11/2019 610 Chapter 02

    11/43

    11

    Asignacin

    Los valores se almacenan en campos(y otras variables) a travs de

    sentencias de asignacin:variable = expression;

    price = cost;

    A variable almacena un solo valor,por lo que cualquier valor anterior sepierde.

  • 8/11/2019 610 Chapter 02

    12/43

    12

    La eleccin de los nombres devariables

    Hay mucho de la libertad sobre la eleccin delos nombres. salo con sabidura!

    Elegir nombres expresivos para hacer el cdigo

    ms fcil de entender:price, amount, name, age, etc.

    Evite una sola letra o nombres crpticos:

    w, t5, xyz123

  • 8/11/2019 610 Chapter 02

    13/43

    13

    Conceptos principales atratarse

    mtodos

    incluyendo mtodos de acceso y

    mutadores sentencias condicionales

    concatenacin de cadenas

    variables locales

  • 8/11/2019 610 Chapter 02

    14/43

    14

    Mtodos

    Mtodos implementan el comportamiento de losobjetos.

    Mtodos tienen una estructura coherente

    compuesta de una cabecera y un cuerpo. Mtodos de acceso proporcionan informacin acerca

    de un objeto.

    Mtodos de mutador alteran el estado de un objeto.

    Otros tipos de mtodos de lograr una variedad detareas.

  • 8/11/2019 610 Chapter 02

    15/43

    15

    Metodo estructura

    La cabecera ofrece la firma del mtodo :public int getPrice()

    La cabecera nos dice : el nombre del mtodo lo parmetros que toma si se devuelve un resultado su visibilidad a los objetos de otras clases

    El cuerpo incluye sentencias del mtodo.

  • 8/11/2019 610 Chapter 02

    16/43

    16

    Mtodos de acceso (GET)

    public int getPrice()

    {

    return price;

    }

    tipo deretorno

    nombre del mtodo

    ista deparmetros(empty)

    inicio y final de un cuerpo de mtodo(bloque)

    sentencia return

    modificador de visibilidad

  • 8/11/2019 610 Chapter 02

    17/43

    17

    Mtodos de acceso

    Un mtodo de acceso siempre tieneun tipo de retorno que no es nula.

    Un mtodo de acceso devuelve unvalor (resultado) del tipo dado en lacabecera.

    El mtodo contiene una sentencia

    return para devolver el valor. NB: Volviendo no imprime!

  • 8/11/2019 610 Chapter 02

    18/43

    19

    Pruebapublic class Maquinacocacola{

    private price;

    public CokeMachine(){

    price = 300

    }

    public int getPrice

    {

    return Price;

    }}

    ;

    ()

    int

    -

    Qu est

    mal aqu?

    (hay cinco

    errores!)

  • 8/11/2019 610 Chapter 02

    19/43

    20

    mtodos mutadores

    Tener una estructura mtodo similar:cabecera y el cuerpo.

    Se utiliza para mutar (es decir, elcambio) el estado de un objeto. Conseguido a travs de cambiar el

    valor de uno o ms campos.

    Normalmente contienen instrucciones deasignacin.

    A menudo reciben parmetros.

  • 8/11/2019 610 Chapter 02

    20/43

    21

    Mutator methods

    Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

    public void insertMoney(int amount)

    {

    balance = balance + amount;

    }

    return typemethod name parameter

    visibility modifier

    assignment statementfield being mutated

  • 8/11/2019 610 Chapter 02

    21/43

    22

    setmutator methods

    Fields often have dedicated setmutator methods.

    These have a simple, distinctiveform: voidreturn type method name related to the field name

    single parameter, with the same type asthe type of the field

    a single assignment statement

  • 8/11/2019 610 Chapter 02

    22/43

    23

    A typical setmethod

    public void setDiscount(int amount)

    {

    discount = amount;

    }

    We can infer that discount

    is a field of type int, i.e:

    private int discount;

  • 8/11/2019 610 Chapter 02

    23/43

    24

    Protective mutators

    A set method does not have to assignthe parameter to the field.

    The parameter may be checked forvalidity and rejected ifinappropriate.

    Mutators thereby protect fields. Mutators support encapsulation.

  • 8/11/2019 610 Chapter 02

    24/43

    25

    Printing from methods

    Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

    public void printTicket()

    {

    // Simulate the printing of a ticket.

    System.out.println("##################");

    System.out.println("# The BlueJ Line");System.out.println("# Ticket");

    System.out.println("# " + price + " cents.");

    System.out.println("##################");

    System.out.println();

    // Update the total collected with the balance.total = total + balance;

    // Clear the balance.

    balance = 0;

    }

  • 8/11/2019 610 Chapter 02

    25/43

    26

    String concatenation

    4 + 59

    "wind" + "ow""window" "Result: " + 6

    "Result: 6" "# " + price + " cents"

    "# 500 cents"

    Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

    overloading

  • 8/11/2019 610 Chapter 02

    26/43

    27

    Quiz

    System.out.println(5 + 6 + "hello");

    System.out.println("hello" + 5 + 6);

    Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

    11hello

    hello56

  • 8/11/2019 610 Chapter 02

    27/43

    28

    Method summary

    Methods implement all object behavior.

    A method has a name and a return type. The return-type may be void.

    A non-voidreturn type means the method willreturn a value to its caller.

    A method might take parameters.

    Parameters bring values in from outside for themethod to use.

  • 8/11/2019 610 Chapter 02

    28/43

    29

    Reflecting on the ticketmachines

    Their behavior is inadequate inseveral ways: No checks on the amounts entered. No refunds.

    No checks for a sensible initialization.

    How can we do better? We need more sophisticated behavior.

    Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

  • 8/11/2019 610 Chapter 02

    29/43

    30

    Making choices in everyday life

    If I have enough money left, then Iwill go out for a meal

    otherwise I will stay home and watcha movie.

  • 8/11/2019 610 Chapter 02

    30/43

    31

    Making a choice in everyday life

    if(I have enough money left) {

    go out for a meal;

    }

    else {stay home and watch a movie;

    }

  • 8/11/2019 610 Chapter 02

    31/43

    32

    Making choices in Java

    Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

    if(perform some test) {Do these statements if the test gave a true result

    }

    else {

    Do these statements if the test gave a false result

    }

    ifkeywordboolean condition to be tested

    actions if condition is true

    actions if condition is falseelsekeyword

  • 8/11/2019 610 Chapter 02

    32/43

    33

    Making a choice in theticket machine

    Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

    public void insertMoney(int amount)

    {

    if(amount > 0) {

    balance = balance + amount;

    }

    else {

    System.out.println(

    "Use a positive amount: " +

    amount);}

    }

  • 8/11/2019 610 Chapter 02

    33/43

    34

    How do we write'refundBalance'?

    Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

  • 8/11/2019 610 Chapter 02

    34/43

    35

    Variables a recap

    Fields are one sort of variable. They store values through the life of an object. They are accessible throughout the class.

    Parameters are another sort of variable: They receive values from outside the method. They help a method complete its task. Each call to the method receives a fresh set of

    values. Parameter values are short lived.

    Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

  • 8/11/2019 610 Chapter 02

    35/43

    36

    Local variables

    Methods can define their own, localvariables: Short lived, like parameters.

    The method sets their values unlikeparameters, they do not receive externalvalues.

    Used for temporarycalculation and storage.

    They exist only as long as the method is beingexecuted. They are only accessible from within the

    method.

  • 8/11/2019 610 Chapter 02

    36/43

    37

    Scope highlighting

  • 8/11/2019 610 Chapter 02

    37/43

    38

    Scope and lifetime

    Each block defines a new scope. Class, method and statement.

    Scopes may be nested: statement block inside another block

    inside a method body inside a classbody.

    Scope is static (textual). Lifetime is dynamic (runtime).

    Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

  • 8/11/2019 610 Chapter 02

    38/43

    39

    Local variables

    Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

    public int refundBalance()

    {

    int amountToRefund;

    amountToRefund = balance;

    balance = 0;

    return amountToRefund;

    }

    A local variable

    No visibilitymodifier

  • 8/11/2019 610 Chapter 02

    39/43

    40

    Scope and lifetime

    The scope of a local variable is theblock in which it is declared.

    The lifetime of a local variable is thetime of execution of the block inwhich it is declared.

    The scope of a field is its whole class. The lifetime of a field is the lifetime

    of its containing object.

  • 8/11/2019 610 Chapter 02

    40/43

    41

    Review (1)

    Class bodies contain fields,constructors and methods.

    Fields store values that determine anobjects state. Constructors initialize objects

    particularly their fields. Methods implement the behavior of

    objects.

    Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

  • 8/11/2019 610 Chapter 02

    41/43

    42

    Review (2)

    Fields, parameters and local variablesare all variables.

    Fields persist for the lifetime of anobject. Parameters are used to receive values

    into a constructor or method. Local variables are used for short-lived

    temporary storage.

    Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

  • 8/11/2019 610 Chapter 02

    42/43

    43

    Review (3)

    Methods have a return type.

    void methods do not return anything.

    non-voidmethods return a value. non-voidmethods have a return

    statement.

  • 8/11/2019 610 Chapter 02

    43/43

    Review (4)

    Correctbehavior often requiresobjects to make decisions.

    Objects can make decisions viaconditional (if) statements.

    A true-or-false test allows one of two

    alternative courses of actions to betaken.