Alice in Action with Java Chapter 9 Methods. Alice in Action with Java2 Non- void vs. void Methods Alice messages –Methods: messages sent where a statement.

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Alice in Action with Java
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Chapter 10 THINKING IN OBJECTS 1 Object Oriented programming Instructor: Dr. Essam H. Houssein.
Static Methods Chapter 4. Chapter Contents Objectives 4.1 Introductory Example: Old MacDonald Had a Farm … 4.2 Getting Started with Methods 4.3 Example:
Chapter 4: Writing Classes
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
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.
Alice in Action with Java Chapter 7 From Alice to Java.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
1 Modularity In “C”. 2 What is Modularity?  Modularity, is the heart of the high level, structured languages.  Means breaking down a big problem into.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Method libraries – baloon prank. Alice in Action with Java2 Method Libraries Repositories for related methods Example: Math class Section objective: build.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Introduction to Methods
1 4.3 Example: Volume of a Sphere Given the radius r, what is the weight of a ball (sphere) of wound twine?Given the radius r, what is the weight of a.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 10 Thinking in Objects.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
1 Simple Methods Chap. 4 Study Sections 4.1 – 4.4 Writing Reusable Formulas.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
© 2007 Lawrenceville Press Slide 1 Chapter 8 Objects  A variable of a data type that is a class. Also called an instance of a class.  Stores data  Can.
1 Chapter 5: Defining Classes. 2 Basics of Classes An object is a member of a class type What is a class? Fields & Methods Types of variables: –Instance:
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
Alice in Action with Java Chapter 8 Types and Expressions.
1 Simple Methods Chap. 4 Study Sections 4.1 – 4.4 Writing Reusable Formulas.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Polymorphism l Constructors.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Class Definitions: The Fundamentals Chapter 6 3/30/15 & 4/2/15 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 4: Writing Classes
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Can perform actions and provide communication
Object Based Programming
Chapter 3 Introduction to Classes, Objects Methods and Strings
Can perform actions and provide communication
Chapter 4: Writing classes
Chapter 6 Methods: A Deeper Look
Classes, Encapsulation, Methods and Constructors (Continued)
Can perform actions and provide communication
CIS 199 Final Review.
Lecture 8 Object Oriented Programming (OOP)
Presentation transcript:

Alice in Action with Java Chapter 9 Methods

Alice in Action with Java2 Non- void vs. void Methods Alice messages –Methods: messages sent where a statement occurs –Functions: messages sent where an expression occurs All messages in Java 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

Alice in Action with Java3 Non- void Methods How getVerse() revises the HokeyPokey program –Takes a String argument representing a bodyPart –Returns a verse that includes the bodyPart –Is called multiple times in one println() statement getVerse() method vs. printVerse() method –getVerse() is a value-returning method –getVerse() can be used for more than display Non- void methods use Java’s return statement return statement pattern: return Expression –Any Java type can be used as a return type

Alice in Action with Java4 Non- void Methods (continued)

Alice in Action with Java5 Non- void Methods (continued)

Alice in Action with Java6 Method Design Procedure for developing a method –Write a user story –Identify the nouns (objects) –Identify the verbs (operations) –Organize the objects and operations into an algorithm Designing the getVerse() method –User story: method returns verse including body part –Body part will be a String object passed by the sender –Verse modified by the argument is returned to sender Locals: variables and constants declared in a method

Alice in Action with Java7 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);

Alice in Action with Java8 Einstein’s Formula (continued)

Alice in Action with Java9 Computing Initials Method for computing the first initial of a name –firstInitial() takes String value called name –First char value is accessed and returned to caller How to use firstInitial() –char initial1 = firstInitial("Homer Jay Simpson"); Method for computing the last initial of a name –lastInitial() takes String value called name –The index of the last space is computed and stored –char value after index of last space is returned

Alice in Action with Java10 Computing Initials (continued)

Alice in Action with Java11 Computing Initials (continued)

Alice in Action with Java12 Computing Initials (continued) Method for computing first and last initials of a name –twoInitials() takes String value called name –String called result is used to build the two initials –name is passed to firstInitial() –Value returned by firstInitial() stored in result –name is passed to lastInitial() –Value returned by lastInitial() stored in result –result is returned to caller and stored in a String Concatenation operation: joins String values result value is built using concatenation operation

Alice in Action with Java13 Computing Initials (continued)

Alice in Action with Java14 Sound Level Program Revisited Sound level program review –Task: compute loudness of a sound –Inputs: reference loudness and distance, new distance Revised program wraps formula in newSPL() –The parameter list corresponds to the three inputs –Sound pressure level is computed in the method body –The result is returned and stored in a long variable The revision makes the computation reusable –Example: newSPL() is also invoked in MethodTester In general, methods make a computation reusable

Alice in Action with Java15 Sound Level Program Revisited (continued)

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

Alice in Action with Java17 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

Alice in Action with Java18 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

Alice in Action with Java19 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

Alice in Action with Java20 Program Design (continued)

Alice in Action with Java21 Program Design (continued)

Alice in Action with Java22 Program Design (continued)

Alice in Action with Java23 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)

Alice in Action with Java24 Program Implementation (continued)

Alice in Action with Java25 Program Implementation (continued)

Alice in Action with Java26 Program Implementation (continued)

Alice in Action with Java27 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

Alice in Action with Java28 Unit Testing (continued)

Alice in Action with Java29 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;

Alice in Action with Java30 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

Alice in Action with Java31 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

Alice in Action with Java32 Box Objects (continued)

Alice in Action with Java33 Box Objects (continued)

Alice in Action with Java34 Box Objects (continued)

Alice in Action with Java35 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

Alice in Action with Java36 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

Alice in Action with Java37 Box Objects (continued)

Alice in Action with Java38 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;}

Alice in Action with Java39 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());

Alice in Action with Java40 Sphere Objects (continued)

Alice in Action with Java41 Sphere Objects (continued)

Alice in Action with Java42 Sphere Objects (continued)

Alice in Action with Java43 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( );

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

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