Presentation is loading. Please wait.

Presentation is loading. Please wait.

Alice in Action with Java Chapter 9 Methods. Alice in Action with Java2 Objectives Use Math methods Use string methods Understand boolean type Build your.

Similar presentations


Presentation on theme: "Alice in Action with Java Chapter 9 Methods. Alice in Action with Java2 Objectives Use Math methods Use string methods Understand boolean type Build your."— Presentation transcript:

1 Alice in Action with Java Chapter 9 Methods

2 Alice in Action with Java2 Objectives Use Math methods Use string methods Understand boolean type Build your own Java methods Define parameters and pass arguments to them Distinguish between class and instance methods Build a method library

3 Alice in Action with Java3 Java’s Math class Provides a set of math functions Part of Java.lang, so you don’t have to import Static methods (no need to create a Math guy) Math methods most often take double arguments Math class constants: Math.E and Math.PI Example: compute volume of a sphere given radius –Formula: volume = 4/3 x PI x radius 3 –Implementation: double volume = 4.0 / 3.0 * Math.PI * Math.pow(radius, 3.0);

4 Alice in Action with Java4 Math Class

5 Alice in Action with Java5 Math Class

6 Alice in Action with Java6 The String Type Used to store a sequence of characters Example: String lastName = "Cat"; Different handles may refer to one String object String literal: 0 or more characters between “ and ” –Escape sequences can also be used in String literals String handle can be set to null or empty string

7 Alice in Action with Java7 The String Type (continued) Instance method: message sent to an object Class method: message sent to a class –Indicated by the word static Java API lists a rich set of String operations Example of instance method sent to String object –char lastInit = lastName.charAt(0); Example of class method sent to String class –String PI_STR = String.valueOf(Math.PI);

8 Alice in Action with Java8 The String Type (continued)

9 Alice in Action with Java9 The String Type (continued)

10 Alice in Action with Java10 The String Type (continued) Concatenation –Joins String values using the + operator –At least one operand must be a String type An illustration of concatenation –String word = "good"; word = word + "bye"; –Second statement refers to a new object –Garbage collector disposes of the de-referenced object += : the concatenation-assignment shortcut – Example: word += "bye";

11 Alice in Action with Java11 The boolean Type Holds one of two values: true (1) or false (0) boolean (logical) expressions –Control flow of execution through a program Relational operators (, =, ==, != ) –Compare two operands and return a boolean value –May also be used to build simple logical expressions Example of a simple boolean expression –boolean seniorStatus = age >= 65; –Produces true if age >= 65; otherwise false

12 Alice in Action with Java12 The boolean Type (continued)

13 Alice in Action with Java13 The boolean Type (continued)

14 Alice in Action with Java14 The boolean Type (continued) Logical operators ( &&, ||, and ! ) –Used to build compound logical expressions Example of a compound logical expression –boolean liqWater; // declare boolean variable liqWater = 0.0 < wTemp && wTemp < 100.0; –wTemp must be > 0 and < 100 to produce true Truth table –Relates combinations of operands to each operator –Shows value produced by each logical operation

15 Alice in Action with Java15 The boolean Type (continued)

16 Alice in Action with Java16 Methods How to perform a method –Send a message to an object or class Building a method in Alice –Click the create new method button –Drag statements into the method Focus of Chapter 9 –Learning how to build methods in Java You have been creating main methods, and might have created other methods also in the last homework

17 Alice in Action with Java17 Introductory Example: The Hokey Pokey Song Problem: write a Java program to display song lyrics Brute force approach –One String object stores the song lyrics –One action displays those lyrics –Implement program using one println() message –Issue: program is about 60 lines long (excessive) A better approach takes advantage of song structure –Each verse only differs by the body part that is moved –Implement program with a single method to print verse –printVerse() takes one argument for the bodyPart

18 Alice in Action with Java18 Introductory Example: The Hokey Pokey Song (continued)

19 Alice in Action with Java19 Introductory Example: The Hokey Pokey Song (continued)

20 Alice in Action with Java20 Introductory Example: The Hokey Pokey Song (continued)

21 Alice in Action with Java21 Methods (continued) Analyzing the first line of printVerse() –public : allows another class access to the method –static : indicates that the message is a class method –void : indicates that the method does not return a value –printVerse : the method’s name –() : contains parameters, such as String bodyPart –{ : indicates the beginning of the method statements Simplified pattern for a Java method [AccessMode] [static] ReturnType MethodName (Params) {Statements}

22 Alice in Action with Java22 Method Design Procedure for developing a method –Figure out inputs and outputs (story) of the whole problem. (Test data here can help) –Figure out what repeats or is complex enough to splice out - > These are your methods Maybe flow chart the main routine Figure out the inputs and outputs for each method List test data for the inputs and outputs Determine Locals: variables and constants declared in a method

23 Exercise for Methods Your task: Print a story that says: I am a lonely cat, and I really like talking to you. I am a sad cat, and I really like talking to you. I am a mad cat, and I really like talking to you. You came home! I am a happy cat, and I really like talking to you. ----- Remember to figure out what your methods will be and what your main program flow will be. Alice in Action with Java23

24 Alice in Action with Java24 Non- void vs. void Methods Alice messages –Methods: just runs statements –Functions: returns a value Java - both are called methods void method in Java –Corresponds to an Alice method –Example: printVerse() non- void method in Java –Corresponds to an Alice function –Must have a return type

25 Alice in Action with Java25 Einstein’s Formula e = m x c 2 : energy = mass x speed of light 2 –The formula itself serves as the user story –Method returns an expression for right side of formula Developing the massToEnergy() method –Method’s return type is a double –Parameter list includes a double type called mass –Speed of light is declared as a constant outside method –Computation is performed within return statement Example of a call to massToEnergy() –double energy = massToEnergy(1.0);

26 Alice in Action with Java26 Einstein’s Formula (continued)

27 Non-void Method exercise Write a method called getBMI that calculates a person’s Body Mass Index. The formula is: BMI = Weight (lb) / (Height (in) x Height (in)) x 703 Example : Someone who is 5'6" (5'6" = 66") and weights 160 lb has a BMI of 160 / (66 x 66) x 703 = 25.8 In your main program, print the following 2 lines: At 66” and 160lb, Ted has a bmi of 25.8 At 55” and 160lb, Mary has a bmi of Extra: Mary and Ted together have an average bmi of ?? Alice in Action with Java27

28 How to start What goes in to the equation  your parameters What gets sent back  your return type What are the steps to get from one to the other  your statements Alice in Action with Java28

29 Alice in Action with Java29 Method Tester Call your method from another class It can call the method many times sending it many different values. It should have one call for each of your test statements. It is just another class with a method called testerNameTested and statements calling the methods it tests.

30 Alice in Action with Java30 Method Libraries Repositories for related methods Example: Math class Section objective: build two method libraries

31 Alice in Action with Java31 Problem Description: Ballooning a Bedroom Problem context –Your friend who plays practical jokes is away –You want to play a practical joke on your friend –You plan to fill your friend’s room with balloons Question: how many balloons should you purchase The question will be answered by a program

32 Alice in Action with Java32 Program Design The problem is concerned with volumes –Find out how many balloon volumes fit in a room volume The balloon is approximated by a sphere –volume sphere = 4/3 x PI x radius 3 The room is approximated by a box –volume box = length x width x height Another issue: whether to use large or small balloons –Large balloons take long to inflate, but fewer are needed –Small balloons inflate quickly, but more are needed

33 Alice in Action with Java33 Program Design (continued) Essentials of the user story –Query the user for the radius of the balloon –Read the radius from the keyboard –Compute the volume of one balloon –Compute the volume of the bedroom Note: dimensions of room are declared as constants –Compute number of balloons needed to fill the bedroom –Display the required number of balloons, with labels Identify nouns and verbs to find objects and operations Organize objects and operations into an algorithm

34 Alice in Action with Java34 Program Design (continued)

35 Alice in Action with Java35 Program Design (continued)

36 Alice in Action with Java36 Program Design (continued)

37 Alice in Action with Java37 Program Implementation First decision: write methods to compute volumes –Rationale: methods allow computations to be reused Second decision: store methods in separate classes –Rationale: makes the program more modular Three classes will be used to implement the program –BalloonPrank : contains the main() driver method –Sphere : library containing sphere methods –Box : library containing box methods Sphere.volume() : takes one argument (radius) Box.volume() : takes three arguments (l, w, h)

38 Alice in Action with Java38 Program Implementation (continued)

39 Alice in Action with Java39 Program Implementation (continued)

40 Alice in Action with Java40 Program Implementation (continued)

41 Alice in Action with Java41 Unit Testing The sole purpose of a test class –Ensure that methods in the program or library work How to implement unit testing –Build a test class with test methods One test method for each method in a program or library –Run the test methods Illustration of unit testing: BoxTester.java –Test method is named testVolume() –testVolume() tests the volume() method of Box –Note: test methods use Java’s assert statement

42 Alice in Action with Java42 Unit Testing (continued)

43 Alice in Action with Java43 Test-Driven Development Reversing the normal testing process –Build the test (this is the starting point) –Use the test to drive subsequent method development Application to the development of methods –Method call indicates number of arguments needed –Number of arguments indicates number of parameters –Type of value expected indicates the return type Example: an initial test for Box.volume() –double vol = Box.volume(2.0, 3.0, 4.0); assert vol == 24.0;

44 Alice in Action with Java44 Instance Methods Method libraries do not use full capabilities of a class –Methods are used independently of objects Leveraging object-oriented programming features –Build objects with instance methods and variables –Send messages to objects Section objective –Learn how to define an instance method

45 Alice in Action with Java45 Box Objects Disadvantage of Box.volume() (a class method) –Box dimensions are passed with each method call Alternative: call method against a Box object –Box initialized once, so values are passed only once Enabling Box class to become an object blueprint –Create instance variables for length, width, height Names of double s: myLength, myWidth, myHeight –Define accessor methods for the instance variables –Create a constructor for a Box object –Add an instance method for computing the volume

46 Alice in Action with Java46 Box Objects (continued)

47 Alice in Action with Java47 Box Objects (continued)

48 Alice in Action with Java48 Box Objects (continued)

49 Alice in Action with Java49 Box Objects (continued) Characteristics of an instance variable –Defined within a class and outside of a method –Omits the keyword static –Each object has its own copy of the instance variables Characteristics of a class variable –Defined within a class and outside of a method –Includes the keyword static –All objects of a class share a class variable Access specifiers: private, protected, public –Guideline: use private access for instance variables

50 Alice in Action with Java50 Box Objects (continued) Purpose of a constructor –Initialize instance variables with user-supplied values Constructor features –The constructor name is always the name of its class –A constructor has no return type (not even void ) The new operator precedes a call to a constructor –Ex 1: Box box1 = new Box(1.1, 2.2, 3.3); –Ex 2: Box box2 = new Box(9.9, 8.8, 7.7); box1 and box2 contain references to Box objects

51 Alice in Action with Java51 Box Objects (continued)

52 Alice in Action with Java52 Box Objects (continued) Instance method –A message sent to an instance of a class –Not defined with the keyword static –Ex: public double volume() {return myLength * myWidth * myHeight;} Invocation: double box1Vol = box1.volume(); Accessor method (getter) –Instance method that returns value of instance variable –Name usually concatenates “get” with an attribute –Ex: public double getWidth() {return myWidth;}

53 Alice in Action with Java53 Sphere Objects Objective: enhance Sphere to support objects New members of Sphere –A single instance variable: double called myRadius –Instance method for calculating Sphere volume –An accessor to return the value of myRadius Sending messages to a Sphere object –System.out.println(sphere1.volume()); –System.out.println(sphere2.volume());

54 Alice in Action with Java54 Sphere Objects (continued)

55 Alice in Action with Java55 Sphere Objects (continued)

56 Alice in Action with Java56 Sphere Objects (continued)

57 Alice in Action with Java57 The BalloonPrank Program Using Objects Program produces same results as the original Difference between original and enhanced versions –Sphere and Box objects model balloon and bedroom Chief benefit of the enhanced version –Sphere and Box classes can be used elsewhere –Ex: Sphere earth = new Sphere(6356.75);

58 Alice in Action with Java58 The BalloonPrank Program Using Objects (continued)

59 Alice in Action with Java59 The BalloonPrank Program Using Objects (continued)

60 Alice in Action with Java60 Classes, Methods, and Design Develop programs using procedure in Section 7.5 Focus on second part of Step 2 –To represent some objects, new types must be built –Ex: Sphere and Box types for balloon and bedroom Focus on the latter part of Step 3 –If necessary, build a new method to perform an action –Ex: volume() methods built for Sphere and Box Abstraction: –Separating high-level behavior from low-level details –Methods and classes improve program abstraction

61 Alice in Action with Java61 Classes, Methods, and Design (continued)

62 Alice in Action with Java62 Keywords, Identifiers, and Scope Keyword: word whose meaning is predefined –Examples: class, int, void, static, double Identifier: word whose meaning is user-defined –Declaration: provides identifier’s meaning to compiler –Examples: Box, Sphere, length, volume() Scope: part of a program where an identifier is known –Scope for local identifiers: method’s statement block –Scope for parameters: treated like local identifiers –Scope for class identifiers: the entire class block

63 Alice in Action with Java63 Summary To make a group of statements reusable, place them within a method A class method includes the word static before the method’s return type An instance method is sent to an object and does not include the word static A void method performs a set of actions, but returns no value A non-void method performs a set of actions, and returns a value

64 Alice in Action with Java64 Summary (continued) Method library: class that serves as a repository for related methods Unit testing: a testing scheme that utilizes a test class containing a set of test methods Test-driven development: a testing scheme that uses desired test outcomes to drive method development Keywords, such as static, are predefined and identifiers, such as variable names, are user-defined Scope: portion of a program where an identifier has meaning


Download ppt "Alice in Action with Java Chapter 9 Methods. Alice in Action with Java2 Objectives Use Math methods Use string methods Understand boolean type Build your."

Similar presentations


Ads by Google