Chapters 4 and 5: Excerpts - PowerPoint PPT Presentation

1 / 20
About This Presentation
Title:

Chapters 4 and 5: Excerpts

Description:

Revised for 2nd Edition by Brian Durney, August 2000. – PowerPoint PPT presentation

Number of Views:40
Avg rating:3.0/5.0
Slides: 21
Provided by: LewRa2
Learn more at: https://cs.nyu.edu
Category:

less

Transcript and Presenter's Notes

Title: Chapters 4 and 5: Excerpts


1
Chapters 4 and 5 Excerpts
Classes, Objects, and Methods
  • Class and Method Definitions
  • Information Hiding and Encapsulation
  • Objects and Reference
  • Parameter passing

2
Using Methods
  • Methods are actions that an object can perform.
  • To use a method you invoke or call it.
  • Example of a method call
  • speciesOfTheMonth.writeOutput()
  • Two basic kinds of methods
  • methods that return a single value
  • void methods that do some action other than
    returning a value

calling objecttells which object will do the
action
parameter list in parenthesesparameters give
info to the method, but in this example there are
no parameters
method nametells which action the object will
perform
3
Return Type of Methods
  • All methods require that the return type be
    specified
  • Return types may be
  • a primitive data type, such as char, int, double,
    etc.
  • a class, such as String, SpeciesFirstTry, etc.
  • void if no value is returned
  • You can use a method anyplace where it is legal
    to use its return type, for example the
    readLineInt() method of SavitchIn returns an
    integer, so this is legal
  • int next SavitchIn.readLineInt()

4
void Method Example
  • The definition of the writeOutput method of
    SpeciesFirstTry
  • Assuming instance variables name, population, and
    growthRate have been defined and assigned
    values, this method performs an action (writes
    values to the screen) but does not return a value

public void writeOutput() System.out.println("
Name " name) System.out.println("Population
" population) System.out.println("Growth
" growthRate "")
5
Return Statement
  • Methods that return a value must execute a return
    statement that includes the value to return
  • For example
  • public int getCount()
  • return count
  • public int count 0

6
Method and Class Naming Conventions
  • Good Programming Practice
  • Use verbs to name void methods
  • they perform an action
  • Use nouns to name methods that return a value
  • they create (return) a piece of data, a thing
  • Start class names with a capital letter
  • Start method names with a lower case letter

7
The main Method
  • A program written to solve a problem (rather than
    define an object) is written as a class with one
    method, main
  • Invoking the class name invokes the main method
  • See the text SpeciesFirstTryDemo
  • Note the basic structure
  • public class SpeciesFirstTryDemo public
    static void main(String args)
    ltstatements that define the main methodgt

8
Local Variables and Blocks
  • A block (a compound statement) is the set of
    statements between a pair of matching braces
    (curly brackets)
  • A variable declared inside a block is known only
    inside that block
  • it is local to the block, therefor it is called a
    local variable
  • when the block finishes executing, local
    variables disappear
  • references to it outside the block cause a
    compile error

9
Local Variables and Blocks
  • Some programming languages (e.g. C and C) allow
    the variable name to be reused outside the local
    block
  • it is confusing and not recommended,
    nevertheless, it is allowed
  • However, a variable name in Java can be declared
    only once for a method
  • although the variable does not exist outside the
    block, other blocks in the same method cannot
    reuse the variable's name

10
When and Where to Declare Variables
  • Declaring variables outside all blocks but within
    the method definition makes them available within
    all the blocks
  • Good programming Practice
  • declare variables just before you use them
  • initialize variables when you declare them
  • do not declare variables inside loops
  • it takes time during execution to create and
    destroy variables, so it is better to do it just
    once for loops)
  • it is ok to declare loop counters in the
    Initialization field of for loops, e.g.for(int
    i0 i lt10 i)
  • the Initialization field executes only once, when
    the for loop is first entered

11
Passing Values to a Method Parameters
  • Some methods can be more flexible (therefor
    useful) if we pass them input values
  • Input values for methods are called passed values
    or parameters
  • Parameters and their data types must be specified
    inside the parentheses of the heading in the
    method definition
  • these are called formal parameters
  • The calling object must put values of the same
    data type, in the same order, inside the
    parentheses of the method invocation
  • these are called arguments, or actual parameters

12
Parameter Passing Example
//Definition of method to double an
integer public int doubleValue(int numberIn)
return 2 numberIn //Invocation of the
method... somewhere in main... ... int next
SavitchIn.readLineInt() System.out.println("Twice
next " doubleValue(next))
  • What is the formal parameter in the method
    definition?
  • numberIn
  • What is the argument in the method invocation?
  • next

13
Pass-By-ValuePrimitive Data Types as Parameters
  • When the method is called, the value of each
    argument is copied (assigned) to its
    corresponding formal parameter
  • The number of arguments must be the same as the
    number of formal parameters
  • The data types of the arguments must be the same
    as the formal parameters and in the same order
  • Formal parameters are initialized to the values
    passed
  • Formal parameters are local to their method
  • Variables used as arguments cannot be changed by
    the method
  • the method only gets a copy of the variable's
    value

14
The Math Class
  • Includes constants Math.PI (approximately
    3.14159) and Math.E (base of natural logarithms
    which is approximately 2.72)
  • Includes three similar static methods round,
    floor, and ceil
  • All three return whole numbers (although they are
    type double)
  • Math.round returns the whole number nearest its
    argument
  • Math.round(3.3) returns 3.0 and Math.round(3.7)
    returns 4.0
  • Math.floor returns the nearest whole number that
    is equal to or less than its argument
  • Math.floor(3.3) returns 3.0 and Math.floor(3.7)
    returns 3.0
  • Math.ceil (short for ceiling) returns the nearest
    whole number that is equal to or greater than its
    argument
  • Math.ceil(3.3) returns 4.0 and Math.ceil(3.7)
    returns 4.0

15
Designing MethodsTop-Down Design
  • In pseudocode, write a list of subtasks that the
    method must do.
  • If you can easily write Java statements for a
    subtask, you are finished with that subtask.
  • If you cannot easily write Java statements for a
    subtask, treat it as a new problem and break it
    up into a list of subtasks.
  • Eventually, all of the subtasks will be small
    enough to easily design and code.
  • Solutions to subtasks might be implemented as
    private helper methods.
  • Top-down design is also known as
    divide-and-conquer or stepwise refinement.

16
Programming Tips forWriting Methods
  • Apply the principle of encapsulation and detail
    hiding by using the public and private modifiers
    judiciously
  • If the user will need the method, make it part of
    the interface by declaring it public
  • If the method is used only within the class
    definition (a helper method, then declare it
    private
  • Create a main method with diagnostic (test) code
    within a class's definition
  • run just the class to execute the diagnostic
    program
  • when the class is used by another program the
    class's main is ignored

17
Testing a Method
  • Test programs are sometimes called driver
    programs
  • Keep it simple test only one new method at a
    time
  • driver program should have only one untested
    method
  • If method A uses method B, there are two
    approaches
  • Bottom up
  • test method B fully before testing A
  • Top down
  • test method A and use a stub for method B
  • A stub is a method that stands in for the final
    version and does little actual work. It usually
    does something as trivial as printing a message
    or returning a fixed value. The idea is to have
    it so simple you are nearly certain it will work.

18
Overloading
  • The same method name has more than one definition
    within the same class
  • Each definition must have a different signature
  • different argument types, a different number of
    arguments, or a different ordering of argument
    types
  • The return type is not part of the signature and
    cannot be used to distinguish between two methods
    with the same name and parameter types

19
Signature
  • the combination of method name and number and
    types of arguments, in order
  • equals(Species) has a different signature than
    equals(String)
  • same method name, different argument types
  • myMethod(1) has a different signature than
    myMethod(1, 2)
  • same method name, different number of arguments
  • myMethod(10, 1.2) has a different signature than
    myMethod(1.2, 10)
  • same method name and number of arguments, but
    different order of argument types

20
Overloading and Argument Type
  • Accidentally using the wrong datatype as an
    argument can invoke a different method
  • For example, see the Pet class in the text
  • set(int) sets the pet's age
  • set(double) sets the pet's weight
  • You want to set the pet's weight to 6 pounds
  • set(6.0) works as you want because the argument
    is type double
  • set(6) will set the age to 6, not the weight,
    since the argument is type int
Write a Comment
User Comments (0)
About PowerShow.com