3-July-2002cse142-D2-Methods © 2002 University of Washington1 Methods CSE 142, Summer 2002 Computer Programming 1

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Starting Out with Java: From Control Structures through Objects Fourth.
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Chapter 5 Functions.
Introduction to Programming with Java, for Beginners Intro OOP with Java Java Program Structure.
Object-Oriented Enterprise Application Development Javadoc Last Updated: 06/30/2001.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Classes and Objects in Java
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
CS 106 Introduction to Computer Science I 03 / 17 / 2008 Instructor: Michael Eckmann.
Introduction to Methods
10-Aug-15 Classes and Objects in Java. 2 Classes and Objects A Java program consists of one or more classes A class is an abstract description of objects.
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.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Chapter 8 Script-free pages. Problem with scripting in JSP When you use scripting (declaration, scriplet, expressions) in your JSP, you actually put Java.
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.
The Java Programming Language
Classes CS 21a: Introduction to Computing I First Semester,
Utilities (Part 2) Implementing static features 1.
CPS120: Introduction to Computer Science Functions.
ECE122 Feb. 22, Any question on Vehicle sample code?
CPS120: Introduction to Computer Science Lecture 14 Functions.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Classes and Objects in Java
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
1 CS161 Introduction to Computer Science Topic #9.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Methods Methods are how we implement actions – actions that objects can do, or actions that can be done to objects. In Alice, we have methods such as move,
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-1 Why Write Methods? Methods are commonly used to break a problem down.
28-June-2002cse142-C2-Classes © 2002 University of Washington1 Classes CSE 142, Summer 2002 Computer Programming 1
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Chapter 3 Implementing Classes
Defining Classes. Why is Java designed this way? Improving our class Creating our own class Using our class Implementing our class.
More Sophisticated Behavior
3 Introduction to Classes and Objects.
Chapter 10: Void Functions
Classes and Objects in Java
Chapter 3: Using Methods, Classes, and Objects
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.
Chapter Topics Chapter 5 discusses the following main topics:
Chapter 3 Introduction to Classes, Objects Methods and Strings
Defining Classes and Methods
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Classes and Objects in Java
Workshop for Programming And Systems Management Teachers
Chapter 6 – Methods Topics are:
Starting Out with Java: From Control Structures through Objects
CLASSES, AND OBJECTS A FIRST LOOK
Overview of Java 6-Apr-19.
Object Oriented Programming in java
Classes CS 21a: Introduction to Computing I
In this class, we will cover:
Classes, Objects and Methods
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Classes and Objects in Java
CMSC 202 Exceptions.
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

3-July-2002cse142-D2-Methods © 2002 University of Washington1 Methods CSE 142, Summer 2002 Computer Programming 1

3-July-2002cse142-D2-Methods © 2002 University of Washington2 Readings and References Reading (reminder) Chapter 5, An Introduction to Programming and Object Oriented Design using Java, by Niño and Hosch Chapter 5, Introduction to Programming in Java, Dugan Other References

3-July-2002cse142-D2-Methods © 2002 University of Washington3 State and Behavior State generally held in one or more “instance variables” for the object there is a set of instance variables for each object For example If class Person defines height as a property of the class then each object of this type (each Person object) will have a height variable and an associated value Behavior defined by the methods that are implemented for the class the same methods are shared by all the objects created from a particular class template

3-July-2002cse142-D2-Methods © 2002 University of Washington4 Dog.java /** * Sample class for demonstrating class structure. */ public class Dog { /** * Create a new Dog. This constructor supplies a default weight of 20 pounds. rate the rate at which this dog eats, specified in pounds/fortnight. */ public Dog(int rate) { consumptionRate = rate; weight = 20; } /** * Provide this dog with a voice. */ public void bark() { System.out.println("Woof! Woof!"); } /** * Provide this dog with a way to rest his bones. */ public void sleep() { System.out.println("Snrf... woof... snrf..."); } This is the bark() method of class Dog

3-July-2002cse142-D2-Methods © 2002 University of Washington5 Method A method is a block of statements that can be invoked to perform a particular action implementing and then calling methods are the way we specify what an object does invoking a method for an object is sometimes called “sending a message to the object” The collection of all the methods defined for a class defines what objects of that class can do For example, if we define methods bark, sleep, eat, and getRate in the Dog class, then all Dog objects created from that class can do all those things. Dog.java

little.bark()big.bark() little.eat(14) big.eat(14) The Dog class Two objects created using the Dog class The Dog class source file Dog.java

3-July-2002cse142-D2-Methods © 2002 University of Washington7 Parameters Some methods know how to implement a little bit of behavior without needing any more information public void bark() { System.out.println("Woof! Woof!"); } A Dog implemented this way will bark exactly the same way every time this method is called But many methods need to know something additional in order to actually perform their task /** * Eat some goodies. There is some weight gain after eating. pounds the number of pounds of food provided. */ public void eat(int pounds) { double coverage = (double)pounds/(double)consumptionRate; … We use parameters (arguments) to provide this additional information

3-July-2002cse142-D2-Methods © 2002 University of Washington8 Specifying the required parameters The method header declares the type and name for each required parameter method eat has one parameter of type int named pounds /** * Eat some goodies. There is some weight gain after eating. pounds the number of pounds of food provided. */ public void eat(int pounds) { double coverage = (double)pounds/(double)consumptionRate; … note that there is a javadoc comment describing the purpose of the parameter

3-July-2002cse142-D2-Methods © 2002 University of Washington9 Parameter declaration Declaring the parameter in the parameter list is just like declaring it in the body of the code The variable pounds has a type ( int ) and it can be used in expressions exactly the way any other variable in the method is used You can declare several parameters in the formal parameter list of a method but try to keep the number down if there are too many, the users of this method (you and other programmers) will have a hard time keeping straight just which parameter is which

3-July-2002cse142-D2-Methods © 2002 University of Washington10 Some examples from class java.lang.String toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale startsWith(String prefix) Tests if this string starts with the specified prefix substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string regionMatches(int toffset, String other, int ooffset, int len) Tests if two string regions are equal

3-July-2002cse142-D2-Methods © 2002 University of Washington11 public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > count) { throw new StringIndexOutOfBoundsException(endIndex); } if (beginIndex > endIndex) { throw new StringIndexOutOfBoundsException(endIndex-beginIndex); } return ((beginIndex == 0) && (endIndex == count)) ? this : new String(offset+beginIndex, endIndex-beginIndex, value); } Parameter variables used in body of method

3-July-2002cse142-D2-Methods © 2002 University of Washington12 What about the values of these parameters? The values (if any required) must be supplied by the caller the compiler checks that the type of the actual values provided matches the type of the parameters that were specified by the method and will not compile the code if they are incompatible rover.bark(); rover.eat(2); rover.bark(); rover.eat(14); The method can vary its behavior in whatever way is appropriate based on the actual values of the parameters

3-July-2002cse142-D2-Methods © 2002 University of Washington13 Supplying an actual value The actual values don’t have to be literals like 2 or 14 You can supply a variable name in the call, and the current value of the variable will be provided to the method int currentFoodAmount = 4; Dog jack = new Dog(2); jack.eat(currentFoodAmount); currentFoodAmount = 20; jack.eat(currentFoodAmount); In this example, the method eat executes twice, once with pounds equal to 4, and then again with pounds equal to 20 Notice that the method always associates the value with the name pounds, even though the caller might be using something else

3-July-2002cse142-D2-Methods © 2002 University of Washington14 The actual arguments can be expressions You can calculate the value to be passed right in the call to the method if that is appropriate Recall: substring(int beginIndex, int endIndex) int beginIndex = 0; String myName = “Doug Johnson”; String twoChar = myName.substring(beginIndex, beginIndex+2); twoChar is now a reference to a String containing “Do” If necessary and possible, the compiler will convert the value provided by the caller to the type of the value that was requested by the method in the formal parameter list

3-July-2002cse142-D2-Methods © 2002 University of Washington15 Returning a value to the caller A method can also return a value to its caller For example, recall the “accessor” methods that allow you to ask an object what some part of its current state is public int getX() public int getWidth() The word int in the above examples specifies the type of value that the method returns /** * Get current X value. the X coordinate */ public int getX() { return x; } SlideX.java

3-July-2002cse142-D2-Methods © 2002 University of Washington16 Documentation for methods Short, useful description of the purpose of the method. javadoc takes the first sentence of this description and uses it in the summary part of the documentation page If there is important background information on how to use the method, it should follow the initial sentence. All parameters use entry for each parameter The return value, if any use tag if appropriate Error exceptions (we will discuss these late in the quarter) use tag if appropriate SlideX.java - generate javadoc

3-July-2002cse142-D2-Methods © 2002 University of Washington17 Constructors A constructor is used to create a new object of a particular class Constructors are special methods that get called with the new operator Dog rover = new Dog(10); we can’t use the rover.bark() pattern to call the Dog() constructor because rover doesn’t have a value until after we call the constructor The name of a constructor is the same as the name of the class in this case Dog(int rate) is a constructor for the class Dog You can think of the constructor as a method that initializes everything according to what the caller has specified, using whatever default values might be appropriate

3-July-2002cse142-D2-Methods © 2002 University of Washington18 Multiple Constructors There are often several constructors for any one class They all have the same name (the name of the class) They must differ in their parameter lists the compiler can tell which constructor you mean by looking at the list of arguments you supply when you call the constructor Rectangle deadTree; Rectangle liveTrunk; deadTree=new Rectangle(150,150,10,50); liveTrunk=new Rectangle(200,210,10,50,Color.orange,true); There is no return value specified for any constructor, because a constructor always fills in the values in a new object Cat.java