cs112 week 08d

Upload: aoexcellence

Post on 02-Jun-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/11/2019 CS112 Week 08d

    1/43

    CS112 Week 08

  • 8/11/2019 CS112 Week 08d

    2/43

    Java How to Program, 9/e

    Copyright 1992-2012 by Pearson Education, Inc. All RightsReserved.

  • 8/11/2019 CS112 Week 08d

    3/43

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    4/43

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    5/43

    Covered in this chapter

    Classes

    Objects

    Methods

    Parameters

    doubleprimitive type

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    6/43

    Objects, or more precisely, the classes objects come from, areessentially reusable software components. There are date objects, time objects, audio objects, video objects, automobile

    objects, people objects, etc. Almost any noun can be reasonably represented as a software object in terms of

    attributes (e.g., name, color and size) and behaviors (e.g., calculating, movingand communicating).

    1992-2012 by Pearson Education, Inc.All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    7/43

    Methods and Classes Performing a task in a program requires a method. The method houses the program statements that actually perform its

    tasks. Hides these statements from its user, just as the accelerator pedal of a

    car hides from the driver the mechanisms of making the car go faster. In Java, we create a program unit called a classto house the set ofmethods that perform the classs tasks.

    A class is similar in concept to a cars engineering drawings, whichhouse the design of an accelerator pedal, steering wheel, and so on.

    1992-2012 by Pearson Education, Inc.All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    8/43

    Instantiation

    Just as someone has to build a car from its engineering

    drawings before you can actually drive a car, you must build an

    object of a class before a program can perform the tasks that

    the classs methods define. An object is then referred to as an instanceof its class.

    1992-2012 by Pearson Education, Inc.All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    9/43

    Reuse Just as a cars engineering drawings can be reused many times to build

    many cars, you can reuse a class many times to build many objects. Reuse of existing classes when building new classes and programs saves

    time and effort. Reuse also helps you build more reliable and effective systems, because

    existing classes and components often have gone through extensivetesting, debugging and performance tuning.

    Just as the notion of interchangeable partswas crucial to the IndustrialRevolution, reusable classes are crucial to the software revolution thathas been spurred by object technology.

    1992-2012 by Pearson Education, Inc.All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    10/43

    Messages and Methods Calls

    When you drive a car, pressing its gas pedal sends a message

    to the car to perform a taskthat is, to go faster.

    Similarly, you send messagesto an object.

    Each message is implemented as a method callthat tells amethod of the object to perform its task.

    1992-2012 by Pearson Education, Inc.All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    11/43

    An object, has attributes that it carries along as its used in aprogram.

    Specified as part of the objects class.

    A bank account object has a balance attribute that represents

    the amount of money in the account. Each bank account object knows the balance in the account it

    represents, but not the balances of the other accounts in the

    bank.

    Attributes are specified by the classs instance variables.

    1992-2012 by Pearson Education, Inc.All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    12/43

    Encapsulation

    Classes encapsulate(i.e., wrap) attributes and methods into

    objectsan objects attributes and methods are intimately

    related.

    Objects may communicate with one another, but theyrenormally not allowed to know how other objects are

    implementedimplementation details arehidden within the

    objects themselves.

    Information hiding, as well see, is crucial to good softwareengineering.

    1992-2012 by Pearson Education, Inc.All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    13/43

    Inheritance

    A new class of objects can be created quickly and conveniently

    by inheritancethe new class absorbs the characteristics of an

    existing class, possibly customizing them and adding unique

    characteristics of its own. In our car analogy, an object of class convertible certainly is

    an object of the more general class automobile, but more

    specifically, the roof can be raised or lowered.

    1992-2012 by Pearson Education, Inc.All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    14/43

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    15/43

    Create a new class (GradeBook)

    Use it to create an object.

    Each class declaration that begins with keyword

    publicmust be stored in a file that has the samename as the class and ends with the .javafile-nameextension.

    Keyword publicis an access modifier.

    Indicates that the class is available to the public

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    16/43

    The mainmethod is called automatically by the JavaVirtual Machine (JVM) when you execute an application.

    Normally, you must call methods explicitly to tell them to

    perform their tasks.

    A publicis available to the public It can be called from methods of other classes.

    The return typespecifies the type of data the method returns

    after performing its task.

    Return type voidindicates that a method will perform atask but will not return (i.e., give back) any information to

    its calling methodwhen it completes its task.

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    17/43

    Method name follows the return type. By convention, method names begin with a lowercase first

    letter and subsequent words in the name begin with acapital letter.

    Empty parentheses after the method name indicate that themethod does not require additional information to performits task.

    Together, everything in the first line of the method istypically called the Method header

    Every methods body is delimited by left and right braces.

    The method body contains one or more statements thatperform the methods task.

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    18/43

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    19/43

    Use class GradeBookin an application. Class GradeBookis not an application because it does not

    contain main.

    Cant execute GradeBook; will receive an error message

    like:Exception in thread "main"java.lang.NoSuchMethodError: main

    Must either declare a separate class that contains a mainmethod or place a mainmethod in class GradeBook.

    To help you prepare for the larger programs, use a separateclass containing method mainto test each new class.

    Some programmers refer to such a class as a driver class.

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    20/43

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    21/43

    Implement GradeBook and GradeBookTest

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    22/43

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    23/43

    A staticmethod (such as main) is special It can be called without first creating an object of the class in

    which the method is declared.

    Typically, you cannot call a method that belongs to

    another class until you create an object of that class.

    Declare a variable of the class type.

    Each new class you create becomes a new type that can be

    used to declare variables and create objects.

    You can declare new class types as needed; this is one reason

    why Java is known as an extensible language.

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    24/43

    Class instance creation expression Keyword newcreates a new object of the class specified to the

    right of the keyword.

    Used to initialize a variable of a class type.

    The parentheses to the right of the class name are required. Parentheses in combination with a class name represent a call

    to a constructor, which is similar to a method but is used only

    at the time an object is created to initialize the objects data.

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    25/43

    Call a method via the class-type variable Variable name followed by a dot separator(.), the method

    name and parentheses.

    Call causes the method to perform its task.

    Any class can contain a mainmethod. The JVM invokes the mainmethod only in the class used to

    execute the application.

    If multiple classes that contain main, then one that is invoked

    is the one in the class named in the javacommand.

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    26/43

    Compiling an Application with Multiple Classes Compile the classes in Fig. 3.1 and Fig. 3.2 before executing.

    Type the command

    javac GradeBook.java GradeBookTest.java

    If the directory containing the application includes only thisapplications files, you can compile all the classes in the

    directory with the command

    javac *.java

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    27/43

    Figure 3.3: UML class diagramfor class GradeBook. Each class is modeled in a class diagram as a rectangle with

    three compartments. Top: contains the class name centered horizontally in boldface type.

    Middle: contains the classs attributes, which correspond to instancevariables (Section 3.5).

    Bottom: contains the classs operations, which correspond tomethods.

    Operations are modeled by listing the operation name

    preceded by an access modifier (in this case +) andfollowed by a set of parentheses.

    The plus sign (+) corresponds to the keyword public.

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    28/43

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    29/43

    Implement class RandomNumber with a Method

    GetANumber_Between_1_and_10

    Use the RandomNumber class in the GuessANumber

    program

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    30/43

    Car analogy Pressing a cars gas pedal sends a message to the car to

    perform a taskmake the car go faster.

    The farther down you press the pedal, the faster the car

    accelerates. Message to the car includes the task to perform and additional

    information that helps the car perform the task.

    Parameter: Additional information a method needs to

    perform its task.

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    31/43

    A method can require one or more parameters thatrepresent additional information it needs to perform its

    task.

    Defined in a comma-separatedparameter list

    Located in the parentheses that follow the method name

    Each parameter must specify a type and an identifier.

    A method call supplies valuescalled argumentsfor

    each of the methods parameters.

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    32/43

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    33/43

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    34/43

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    35/43

    Scannermethod nextLine Reads characters typed by the user until the newline character is

    encountered Returns a Stringcontaining the characters up to, but not including,

    the newline PressEnterto submit the string to the program. PressingEnterinserts a newline character at the end of the characters

    the user typed. The newline character is discarded by nextLine.

    Scannermethod next Reads individual words

    Reads characters until a white-space character is encountered, thenreturns a String(the white-space character is discarded).

    Information after the first white-space character can be read by otherstatements that call the Scanners methods later in the program-.

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    36/43

    More on Arguments and Parameters The number of arguments in a method call must match the

    number of parameters in the parameter list of the methods

    declaration.

    The argument types in the method call must be consistentwith the types of the corresponding parameters in the

    methods declaration.

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    37/43

  • 8/11/2019 CS112 Week 08d

    38/43

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    39/43

    Notes on importDeclarations Classes Systemand Stringare in package java.lang

    Implicitly imported into every Java program

    Can use the java.langclasses without explicitly importing them

    Most classes youll use in Java programs must be imported explicitly.

    Classes that are compiled in the same directory on disk are in the

    same packageknown as the default package.

    Classes in the same package are implicitly imported into the source-

    code files of other classes in the same package.

    An importdeclaration is not required if you always refer to a classvia its fully qualified class name

    Package name followed by a dot (.) and the class name.

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    40/43

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    41/43

    Enhance class RandomNumber with a Method

    GetANumber(int lo, int hi)

    Use the RandomNumber class in the GuessANumber

    program

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    42/43

    Copyright 1992-2012 by PearsonEducation, Inc. All Rights Reserved.

  • 8/11/2019 CS112 Week 08d

    43/43

    1. Define the main statements used in a program (8 points)2. What are the main functions of the declaration statement (4 points) ?

    3. What are the main functions of the conditional statement (4 points)?

    4. What are the main functions of the iterative statement (4 points)?

    5. Implement an Odd/Even game (80 points)

    User is to guess if the computer generated number is odd or even

    Hint: Use the mod operator

    Allow player to play until done

    Keep track of winnings

    Announce winner at the end (how many games in all, how many games each player won, and who is

    the winneror was the game tie)

    6. Bonus (5 points)

    Why the following statements do not work

    1. String s1;

    2. s1 = 123;

    3. if (s1 = 123)println(Equal);