Developing and Using Methods

download Developing and Using Methods

of 32

Transcript of Developing and Using Methods

  • 8/7/2019 Developing and Using Methods

    1/32

    1

  • 8/7/2019 Developing and Using Methods

    2/32

    2

  • 8/7/2019 Developing and Using Methods

    3/32

    Most of the code you write for a class is contained within oneor more methods. Methods let you divide the work thatyour program does into separate logical tasks or behaviors.

    For example, you might want to develop a program thatcalculates and displays a total. Although all of the code toperform these tasks can be put into one method, groupingthe tasks together can create better-object oriented

    programs. In other words, split tasks into chunks so thateach method can be used independently. For example, youmight want to invoke the method that calculates the totalin one class, but does not display the result of thecalculation.

    3

  • 8/7/2019 Developing and Using Methods

    4/32

    where:

    *modifier is the keyword that modify the way methods are used. It isoptional indicated by square bracket.*return_type- is the type of value returned from a method that can be usedelsewhere in the program. Methods can return only one item (literal value,variable, object reference, and so on. If nothing is to be returned, thekeywordvoid must be specified as the return type.

    *method_identifier is the name of the method.*arguments list of variables whose values are passed to the method foruse by the method. This is optional as well.*method_code_block is a sequence of statement that the methodperforms.

    4

  • 8/7/2019 Developing and Using Methods

    5/32

    The basic form of a method accepts no arguments and returns nothing .The following display method from the Shirt class is a basic method.

    5

  • 8/7/2019 Developing and Using Methods

    6/32

    To invoke, or execute, a method in a different class, you can use the dot (.)operator with an object reference variable just as you do to access thepublic variables of an object. The following code example shows theShirtTest class.

    In this example, an object reference variable called myShirt is declared

    and initialized to a Shirt object on Line 6 and 7. The myShirt object

    reference variable then invokes the display method within the Shirt

    object (Line 9). 6

  • 8/7/2019 Developing and Using Methods

    7/32

    Calling and Working Methods

    In the previous example, the ShirtTest class calls the display method fromwithin another method (the main method). Therefore, the mainmethod is referred to as the calling method because it is invoking orcalling another method to do some work. Conversely, the displaymethod is referred to as the worker method because it does some workfor the main method.

    7

  • 8/7/2019 Developing and Using Methods

    8/32

    Invoking Methods in the Same Class

    Calling a method in the same class is easy. Just include the name of theworker method and its arguments, if any.The following is a code example containing a class with one method that

    calls another method in the same class.

    8

  • 8/7/2019 Developing and Using Methods

    9/32

    9

  • 8/7/2019 Developing and Using Methods

    10/32

    The setfloor method invokes the goUpand goDown method (Lines 37 and 40.)

    All three methods are within the Elevator

    class. 10

  • 8/7/2019 Developing and Using Methods

    11/32

    Self-Check Select the method declarations that adhere e to the method

    declaration syntax.

    a. public displayInfo()b. public void displayInfoc. public String getColor()d. public void displayInfo()

    e. public setColor (int Color) 11

  • 8/7/2019 Developing and Using Methods

    12/32

    12

  • 8/7/2019 Developing and Using Methods

    13/32

    Many methods that you declare or use from the Java technology class libraries

    accept arguments. For example, the following setFloor method from theElevator class accepts an int desiredFloor value, which is used in the body ofthe method.

    13

  • 8/7/2019 Developing and Using Methods

    14/32

    Recall that the main that you have been using in your testclasses must also be written so that it accepts arguments:one or more (an array) of references to String objects.

    public static void main (String args[])

    To pass arguments from one method to another, include the arguments in theparentheses of the method call. You can pass literal values or variables asarguments. Similar to assigning literal values to variables, use quotation marksaround the literal string, use the letter F after a float, and so on.

    List the arguments in the same order in which they are listed in the declaration ofthe worker method and pass all required arguments. The compiler then checks tosee if the type, order, and number of parameters you pass matches the type, orderand number of the parameters a method accepts.

    Note: You do not have to use the same variables names as arguments wheninvoking a method. However, variable names must be of a compatible data type. 14

  • 8/7/2019 Developing and Using Methods

    15/32

    The following example shows a numeric value being passed to amethod that performs an operation using the value.

    //ElevatorTest.java

    15

  • 8/7/2019 Developing and Using Methods

    16/32

    This example invokes the setFloor method with an integer value to setthe destination floor (Line 19).

    16

  • 8/7/2019 Developing and Using Methods

    17/32

    y Most of the method declarations that you have seen donot have a return value (void). However, many of themethods you will create will have return values and manymethods in the Java class libraries also have return values.

    y To declare a method that returns a value, place the type ofthe value you want the method to return in front of themethod identifier. For example, the following methoddeclaration accepts two int types and returns an int type:

    public intsum (int numberOne, int numberTwo)

    Note: A method can return only one value but can acceptmultiple arguments.

    17

  • 8/7/2019 Developing and Using Methods

    18/32

    y To return a value from a method, use the returnkeyword. For example, the following code returns thecurrent value held in the sum variable.

    public intsum (int numberOne, int numberTwo) {int result = numberOne + numberTwo;

    return result;}

    The following getFloor method in the Elevator class returns

    the current value held in the currentFloor variable.public int getFloor() {return currentFloor;

    }

    18

  • 8/7/2019 Developing and Using Methods

    19/32

    y If you invoke a method that returns a value, such as in the previous getFloor method, youcan use the return value in the calling method.

    y The following code example contains a test class that creates an instance of the Elevatorclass and invokes its getFloor method, expecting an int return value.

    //Save as ElevatorTestTwo.java

    19

  • 8/7/2019 Developing and Using Methods

    20/32

    The variable curFloor is declared on Line 20 and is used to receivethe integer return value from the getFloor method in the Elevatorclass.

    20

  • 8/7/2019 Developing and Using Methods

    21/32

    y So far, you have learned how to access methods and variables by creating an

    object of the class that the method or variable belongs to and invoking themethod or accessing the variable (if it is a public variable). Methods andvariables that are unique to an instance are called instance methods andinstance variables.

    y You have also been using methods that do not require object instantiation,such as the main method. These are called class methods or static methods;

    you can invoke them without creating an object first.y Similarly, the Java programming language allows you to create static variables

    or class variables, which you can use without creating an object.

    y Note: The main method is a static method that you have already used. You donot have to create an object instance to use the main method.

    Static methods are declared using the static keyword. Following is the methoddeclaration for the getProperties method in the System class in the Java API.

    21

  • 8/7/2019 Developing and Using Methods

    22/32

    y Because static or class methods are not part of any object instance (just the class), you

    should not use an object reference variable to invoke them. Instead, use the classname.The syntax for invoking a static method is:

    Following is an example of a method that could be added to the Shirt class to convert numericalshirt sizes to sized, such as small, medium, or large. This method is a static method because:

    It does not directly use any attributes of the Shirtclass.You might want to invoke the method even if you do not have a Shirt object.

    22

  • 8/7/2019 Developing and Using Methods

    23/32

    y The convertShirtSize method accepts a numerical size, determines thecorresponding character size (S, M, L, or X), and returns the character

    size.y For example, to access the static method convert ShirtSize of Shirt class:char size= Shirt.convertShirtSize(16);

    23

    You can also use the static keyword to declare that there can only be one copy ofthe variable in memory associated with a class, not a copy for each object instance.For example:

    static double salesTax = 8.25;

    You should use the class name to access a static variable. The syntax for invoking astatic variable is:Classname.variable;

    For example, to access the value the static variable for PI in the Math class:

    double myPI;

    myPI = Math.PI;

  • 8/7/2019 Developing and Using Methods

    24/32

    24

  • 8/7/2019 Developing and Using Methods

    25/32

    Self-Check: Select the statements that are true about instance methodsand variables

    a. Instance variables are unique to individual objects.b. Instance methods and variables require object instantiation.c. Instance methods and variables do not require object instantiation.d. Instance methods and variables are declared with the instance

    keyword.

    e. Instance methods and variables are often accessed by using an objectreference variable.

    Self-Check: Select the statements that are true about static methods orvariables.

    a. Static methods and variables are unique to individual objects.b. Static methods and variables require object instantiation.c. Static methods and variables do not require object instantiation.d. Static methods and variables are declared with the static keyword.e. Static methods are often invoked using the class name.

    25

  • 8/7/2019 Developing and Using Methods

    26/32

    In the Java programming language, there can be several methods in a class that have the same name but

    different arguments (different method signatures). This concept is called method overloading.F

    or example ,you might want to create several methods to add two numbers, such as two int types or two float types.

    With method overloading, you can create several methods with the same name and different signatures. For

    example, the following code example contains several sum methods, each accepting a different set of

    arguments.

    26

  • 8/7/2019 Developing and Using Methods

    27/32

    27

    To invoke either of the previous sum methods, the compiler compares the method signature inyour method invocation against the method signatures in a class. For example, following is amain method that invokes each of the previous sum methods within a Calculator object.

  • 8/7/2019 Developing and Using Methods

    28/32

    28

    You an print Strings, ints, floats and so on, using the System.out.println method, becauseit is overloaded with different arguments, for different data types.

    Without overloading, you would need to create multiple methods with different names to

    print different data types, such as printlnint, printlnfloat and so on. Or you would have todo a lot of conversion from one type to another type before using a method.

  • 8/7/2019 Developing and Using Methods

    29/32

    y You can use overloading to create several methods with the samename but with a different number of parameters. For example, youcould create three sum methods, each with a different number ofarguments to add together.

    29

    The following example on the next page is a code example that contains anoverloaded method with different arguments.

    //ShirtTwo.java

  • 8/7/2019 Developing and Using Methods

    30/32

    30

  • 8/7/2019 Developing and Using Methods

    31/32

    31

    The ShirtTwo class has a method , setShirtInformation, which is overloadedtwice: once to accept a colorCode (Line 18) value and a second time to accept acolorCode and quantityInStock (Line 25) values.

    The next code creates three objects instances of the ShirtTwo class and uses their

    overloaded methods.

  • 8/7/2019 Developing and Using Methods

    32/32

    32

    The ShirtTwoTest class invokes the overloaded setShirtInfo by calling it threetimes.