CMSC 150 METHODS AND CLASSES CS 150: Wed 25 Jan 2012.

Slides:



Advertisements
Similar presentations
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Advertisements

1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Java Basics M Taimoor Khan
Introduction to Computers and Programming Lecture 11: Introduction to Methods Professor: Evan Korth New York University.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Objects, Methods, Parameters, Input Lecture 5, Thu Jan
Chapter 41 Defining Classes and Methods Chapter 4.
Introduction to Computers and Programming Introduction to Methods in Java.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
CS 201 Functions Debzani Deb.
Introduction to Computers and Programming Strings Professor: Evan Korth New York University.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Understanding class definitions Looking inside classes.
 2003 Prentice Hall, Inc. All rights reserved Introduction Modules –Small pieces of a problem e.g., divide and conquer –Facilitate design, implementation,
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Writing Classes (Chapter 4)
Dale Roberts Procedural Programming using Java Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and.
Week 3 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
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.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in.
CSE 131 Computer Science 1 Module 1: (basics of Java)
Classes CS 21a: Introduction to Computing I First Semester,
1 Introduction Modules  Most computer programs solve much larger problem than the examples in last sessions.  The problem is more manageable and easy.
More arrays Primitive vs. reference parameters. Arrays as parameters to functions.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Flow of Control Part 1: Selection
142 F -1 Functions chapter 3 of the text int main(void) { double x,y,z; … x = cube(y/3.0); … printf(“%f cubed is %f”,x,cube(x)); … return 0; } double cube(double.
Procedural programming in Java Methods, parameters and return values.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
CMSC 150 CLASSES CS 150: Mon 6 Feb 2012 Images: Library of Congress.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
CMSC 150 METHODS AND CLASSES CS 150: Wed 25 Jan 2012.
Creating and Using Class Methods. Definition Class Object.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
A High Flying Overview CS139 – Fall 2006 How far we have come.
Introduction Modules Small pieces of a problem ▴ e.g., divide and conquer Facilitate design, implementation, operation and maintenance of large programs.
Invoking methods in the Java library. Jargon: method invocation Terminology: Invoking a method = executing a method Other phrases with exactly the same.
Mid-Year Review. Coding Problems In general, solve the coding problems by doing it piece by piece. Makes it easier to think about Break parts of code.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Chapter 7 User-Defined Methods.
Suppose we want to print out the word MISSISSIPPI in big letters.
Java Primer 1: Types, Classes and Operators
Methods Chapter 6.
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.
CS139 – Fall 2010 How far we have come
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Chapter 6 Methods: A Deeper Look
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
IFS410 Advanced Analysis and Design
CS2011 Introduction to Programming I Methods (I)
CS2011 Introduction to Programming I Arrays (I)
Chapter 6 Methods.
Classes CS 21a: Introduction to Computing I
Corresponds with Chapter 5
Introduction to Methods and Interfaces
Presentation transcript:

CMSC 150 METHODS AND CLASSES CS 150: Wed 25 Jan 2012

Remember the length “method”? String message = “Hello, Watson”; System.out.println( message.length() ); // prints 13  Method – useful code packaged with a name  In Java, methods belong to classes  With an object like message, use the object variable to “call” the method  works on information inside the object message refers to 2

Why write a method? 3  Code can get very long and unwieldy  Methods let us break up code into logical chunks  Readability – with appropriately named methods, your code is easier to read and follow  Reuse – make repeated code into a method. Write once, use many times.

Why write a method? 4  Code can get very long and unwieldy  Methods let us break up code into logical chunks  Readability – with appropriately named methods, your code is easier to read and follow  Reuse – make repeated code into a method. Write once, use many times. MODULARITY

Writing methods 5 public static method-name ( parameters ) { statements; return ;// Details later }

Writing methods 6 public static method-name ( parameters ) { statements; return ;// Details later } What “kind” of Method this is – More on this later.

Writing methods 7 public static method-name ( parameters ) { statements; return ;// Details later } Does this method produce a value, and if so, what type?

Writing methods 8 public static method-name ( parameters ) { statements; return ;// Details later } What name is used to “invoke” this method?

Writing methods 9 public static method-name ( parameters ) { statements; return ;// Details later } What information is expected from the caller in order to run this method? (Can be empty.)

Writing methods 10 public static method-name ( parameters ) { statements; return ;// Details later } The first line of a method is called the “method header” or “method signature”

Writing methods 11 public static method-name ( parameters ) { statements; return ;// Details later } What’s inside is called the “method body”

Writing methods 12 public static method-name ( parameters ) { statements; return ;// Details later } Statements executed when this method is called.

Writing methods 13 public static method-name ( parameters ) { statements; return ;// Details later } If the method “returns a value,” this is how we make that happen.

Example: Back to FunBrain… 14

Example: Back to FunBrain… 15 Hmm… looks suspiciously like a method…

Example: Back to FunBrain… 16 Check the guess against the secret number and generate a message to the user. Let’s make it into a method.

Parameter passing 17 Formal parameter list

Parameter passing 18 Actual parameter list

Parameter passing 19 Can be any expression that evaluates to the type of the matching formal parameter.

What happens in memory? 20 … = checkGuess( userGuess, randomNumber, guesses ); userGuess randomNumber guesses … Memory used for variables in main() Memory used for variables in main()

What happens in memory? 21 … = checkGuess( userGuess, randomNumber, guesses ); public static String checkGuess ( int currentGuess, int secret, int numGuesses ){ … userGuess randomNumber guesses … currentGuess secret numGuesses Memory used for formal parameters in checkGuess Memory used for formal parameters in checkGuess

What happens in memory? 22 … = checkGuess( userGuess, randomNumber, guesses ); public static String checkGuess ( int currentGuess, int secret, int numGuesses ){ … userGuess randomNumber guesses … currentGuess secret numGuesses When method call is made, values stored in the arguments… …are copied into the formal parameters When method call is made, values stored in the arguments… …are copied into the formal parameters

What happens in memory? 23 … = checkGuess( userGuess, randomNumber, guesses ); public static String checkGuess ( int currentGuess, int secret, int numGuesses ){ … userGuess randomNumber guesses … currentGuess secret numGuesses Arguments & formal parameters initially have the same values… but occupy different spaces in memory Arguments & formal parameters initially have the same values… but occupy different spaces in memory

Method facts 24  In Java, parameters are “passed by value”  (AKA “pass by copy”)  Each call to a method executes in its own memory space  Function: a method that creates and “returns” a value  Procedure: a method that only does work and returns no value (i.e., return type “void”)

Classes in Java 25  Classes contain two things:  methods (also called “behavior”)  data (also called “state”)  Encapsulate related data & methods  A good way of structuring large programs  e.g,. the Java libraries String class Random class Scanner class

Example: String 26  What’s the data for a String object?  The sequence of characters it was initialized with  The length of the sequence  What behavior is available?  length()  charAt(int pos)  indexOf(char c)  substring(int begin, int pastEnd)  … it goes on and on …

Example: String 27  What’s the data for a String object?  The sequence of characters it was initialized with  The length of the sequence  What behavior is available?  length()  charAt(int pos)  indexOf(char c)  substring(int begin, int pastEnd)  … it goes on and on …

Methods with different jobs 28  Some methods let you request information from the class  “Accessor” methods  names often start with “get” (but not always)  e.g., charAt method in String class  Some methods cause a change to the state (i.e., data) held by the class  “Mutator” methods  names may start with “set” (but not always)  e.g., setSeed method in Random class

In order to use a class… 29  … need to know what methods it provides  … need to know what parameters they expect  … need to know how the methods behave  … don’t need to know how they were written  Application Programming Interface (API) Application Programming Interface  Again, need a variable of that class type  Use that variable to call methods in the class

Next lab, who you gonna call? 30

Lab setup 31  What we will give you:  GameBoard Class  Room Class  Ghostbusters skeleton  API documentation for GameBoard and Room  What you will write:  Several methods in Ghostbusters needed by GameBoard to run the game  Your methods will use methods from GameBoard and Room

Your methods 32  public void setupGame()  Sets up the initial game configuration (similar to Wumpus)  public boolean handleMove( String direction )  Logic to control Ghostbuster moving from room to room  public void handleFire( String direction )  Logic to control Ghostbuster firing proton Slimer  public boolean checkForLoss()  Determine if the Ghostbuster encountered Slimer or a portal  public void checkForGhostTrap()  Determine if the Ghostbuster found a desirable ghost trap