Methods - PowerPoint PPT Presentation

1 / 14
About This Presentation
Title:

Methods

Description:

If a method is in the same class, you execute those declarations and statements ... If the method belongs to some other object, you execute it by sending a ... – PowerPoint PPT presentation

Number of Views:93
Avg rating:3.0/5.0
Slides: 15
Provided by: DavidMa6
Category:
Tags: method | methods

less

Transcript and Presenter's Notes

Title: Methods


1
Methods
2
About methods
  • A method is a named group of declarations and
    statements
  • If a method is in the same class, you execute
    those declarations and statements by calling the
    method
  • If the method belongs to some other object, you
    execute it by sending a message to that object
  • When you call the method, you can give it
    parameters (information, such as numbers, going
    into the method)
  • A method typically has a return value (a single
    piece of information coming out of the method)

3
Example method
  • Inside a CokeMachine class, you might have this
    method
  • public void insertCoin(int coin) // coin is
    a parameter if (coin 5 coin 10
    coin 25) amountEntered
    amountEntered coin
  • Inside the CokeMachine class, you might have code
    like this
  • int dime 10insertCoin(dime) // this is a
    call to the insertCoin method
  • In some other class, you might have code like
    this
  • CokeMachine cheater new CokeMachine()
    CokeMachine honestAbe new CokeMachine() int
    dime 10honestAbe.insertCoin(dime) // this
    is a message to honestAbe

4
Why methods?
  • Methods help you break up a complex problem into
    simpler subproblems, which you can solve
    separately
  • Methods can use other methods, but should not
    depend on the inner workings of those other
    methods--just what they do, not how they do it
  • Methods allow you to give names to parts of your
    computation, thus making your program more
    readable
  • Readability is essential in good programming
  • Proper choice of method names is important
  • Verbs are usually best, since methods do
    something
  • If you have anything the least bit complicated to
    compute, you should write (and debug) it in only
    one place
  • This is an application of the DRY principle
    (Dont Repeat Yourself)
  • Methods are very good for putting code in only
    one place

5
Defining a method
  • A method has the syntax
  • access return-type method-name(parameters)
    method-variables code
  • The access (public, protected, or private) is
    optional
  • Example
  • private boolean isAdult(int age) int
    magicAge 21 return age gt magicAge
  • Example
  • double average(int a, int b) return (a b)
    / 2.0

6
Returning a result from a method
  • If a method is to return a result, it must
    specify the type of the result
  • boolean isAdult (
  • You must use a return statement to exit the
    method with a result of the correct type
  • return age gt magicAge

7
Returning no result from a method
  • The keyword void is used to indicate that a
    method doesnt return a value
  • The return statement must not specify a value
  • Example
  • void printAge(String name, int age)
    System.out.println(name " is " age " years
    old.") return
  • There are two ways to return from a void method
  • Execute a return statement
  • Reach the closing brace of the method

8
Instance variables
  • A variable declared within a class (but not
    within a method) is an instance variable
  • Every object (instance) of that class has its
    own variable with that name
  • Example Every CokeMachine has its own
    amountEntered
  • Instance variables are visible--available for
    use--everywhere within the class in which they
    are defined
  • Instance variables should almost always be marked
    private, so that other classes cannot see them
  • Example You dont want a Customer object to be
    able to change the amountEntered in a CokeMachine
    without inserting coins
  • Every instance variable should say something
    meaningful about its object

9
Scope of variables
  • Parameters to a method are visible throughout the
    method
  • Parameters are discarded when the method returns
  • Variables declared within a block (between and
    ) are visible from where they are declared up to
    the end of the block
  • These variables are discarded when the block is
    exited
  • Example
  • public double average(double x, double y, double
    z) // x, y, and z are visible throughout
    this method double count 3.0 // count is
    visible from here forward double avg (x y
    z) / count // avg is visible from here forward
    return avg // the value of avg is returned,
    but the variable itself, //
    and the variable count, are discarded
  • Note that count and avg could be instance
    variables, but since they dont say anything
    about the object they are in, this would be very
    poor style

10
Methods and static methods
  • Java has two kinds of methods static methods and
    non-static methods (also know as instance
    methods)
  • However, before we can talk about what it means
    to be static, we have to learn a lot more about
    classes and objects
  • Most methods you write should not, and will not
    be static
  • Every Java program has a public static
    void main(String args)method
  • This starts us in a static context
  • To escape from static, I recommend starting
    every program in a certain way, as shown on the
    next slide

11
Escaping from static
  • class MyClass public static void
    main(String args) new
    MyClass().run() void run()
    // Your real code begins here
  • You can replace the names MyClass and run with
    names of your choice, but notice that each name
    occurs in two places, and they have to match up

12
Documenting a method
  • Javadoc comments start with / and end with /,
    and are put immediately before the method
  • The text is written as if the method description
    began with the words This method...
  • The comment ends with the following tags
  • _at_param name description (one for each
    parameter)
  • The description tells what information the named
    parameter provides
  • You dont need to mention the parameter
    typeJavadoc knows that
  • If any instance variables are used, their use
    should be described
  • References to the object should be with this
    this Tree, this JPanel, etc.
  • _at_return description
  • A description of the value that is returned (omit
    if void)
  • _at_throws exception cause (one for each
    Exception)
  • Tells what condition will cause this Exception to
    be thrown
  • HTML markup may be used within the Javadoc
    comment
  • To generate the actual documentation from the
    comments (in Eclipse), do Project ? Generate
    Javadoc...

13
Example Javadoc documentation
  • public class Pair private static final long
    serialVersionUID 1L private Student
    student1 private Student student2 . .
    . / Returns one of the two students
    in this pair. ltigtThe order of students is
    irrelevantlt/igt and should not be depended upon.
    _at_param which 1 or 2. _at_return
    One of the students in this pair. /
    public Student getStudent(int which) if
    (which 1) return student1 else if
    (which 2) return student2 else
    error("There is no student " which)
    return null . . .

14
The End
Though this be madness, yet there is method in
it.
--Shakespeare, Hamlet
Write a Comment
User Comments (0)
About PowerShow.com