COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.

Slides:



Advertisements
Similar presentations
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Chapter 4: Writing Classes
Chapter 5 Functions.
Chapter 3, More on Classes & Methods Clark Savage Turner, J.D., Ph.D. Copyright 2003 CSTurner, from notes and text.
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
Chapter 6: User-Defined Functions I
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP Introduction to Programming Adrian Ilie July 13, 2005.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Chapter 6: User-Defined Functions I
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Methods in Java Selim Aksoy Bilkent University Department of Computer Engineering
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Writing Classes (Chapter 4)
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Procedural programming in Java Methods, parameters and return values.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
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.
CiS 260: App Dev I. 2 Introduction to Methods n A method (or ________) is a segment of code that performs a specific task. n Advantages of modular program.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 4: Writing Classes. 2 b We've been using predefined classes. Now we will learn to write our own classes to define new objects b Chapter 4 focuses.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
C# Programming Methods.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Object-Oriented Design Chapter 7 1. Objectives You will be able to Use the this reference in a Java program. Use the static modifier for member variables.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Functions + Overloading + Scope
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Chapter 6: User-Defined Functions I
Chapter 4: Writing Classes
Chapter 4: Writing Classes
Methods.
User-Defined Functions
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.
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)
Chapter 4 Writing Classes.
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Corresponds with Chapter 5
Presentation transcript:

COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004

Anatomy of a Class A class contains data declarations and method declarations int width; int length; Data declarations Method declarations (operations)

Writing a class public class Rectangle { // data members private int width; private int length; // methods public double computeArea() … public static void main() … }

Why Use Methods? To divide complex programs into manageable pieces Abstraction –provide an operation to be performed on an object (ex: computeArea) Code Re-use –write a small piece of code that can be used (called) multiple times (saves typing)

Methods Pre-defined methods –provided by Java standard library –we've used these before –Math class (Math.pow, Math.sqrt,...) –Integer class (Integer.parseInt,...) User-defined methods –you write these

Method as a Black Box METHOD Input parameters Internal data members of the class Return value A method can use input parameters and internal data members of the class It may modify the value of internal data members It may also return a value

Control Flow Program control flow –execution always begins with the first statement in the method main –other methods execute only when called Method control flow –when a method is invoked, the flow of control jumps to the method and the computer executes its code –when complete, the flow of control returns to the place where the method was called and the computer continues executing code Test this with the debugger!

Example: Rectangle.java

Using Methods What You Need To Know 1.Name of the method 2.Number of parameters 3.Data type of each parameter 4.Data type of value computed (returned) by the method 5.The code required to accomplish the task

Method Declaration Specifies the code that will be executed when the method is invoked (or called) Located inside a class definition Contains –method header –method body

Method Header public static int countCharInWord (char ch, String word) method name return type formal parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter A method declaration begins with a method header visibility modifiers

Return Value Value-returning methods –The method returns the result of some operations –Like mathematical functions –Return one single value Void methods –Perform operations but return no value

Value-Returning Methods Think mathematical function f(x) = 2x + 5f(x, y) = 2x + y f(1) = 7f(1, 5) = 7 f(2) = 9f(2, 3) = 7 f(3) = 11f(3, 1) = 7 Can have multiple arguments (parameters) Only one result of the function

Value-Returning Methods Uses Save the value for future calculation Use the value in a calculation Print the value x = Math.pow (y, 2); z = a + Math.pow (y, 2) + x; System.out.println (Math.pow (y, 2));

int number = countCharInWord ('e', "Heels"); 2 Return Type Indicates the type of value that the method evaluates to: –primitive data type –class name –void  reserved word indicating that nothing is returned When a value is returned, the method call is replaced with the returned value

The return Statement Tells the computer to "return" back to where the call was originally made. Specifies the value that will be returned return expression; The data type of expression must match the method's return type Methods with return types of void usually don't (but can) have a return statement Value-returning methods must have at least one return statement

Using return public static double larger (double x, double y) { double max; if(x >= y) max = x; else max = y; return max; } public static double larger (double x, double y) { if(x >= y) return x; else return y; } These are equivalent methods.

Example: Rectangle.java Add computePerimeter( )

Void Methods Do not return a value Have a return type of void Similar in structure to value-returning methods Call to method is always a stand-alone statement Can use return statement to exit method early

Example: Rectangle.java Add printPerimeter( )

The main Method The main method looks just like all other methods public static void main (String[] args) modifiersreturn type method name parameter list

Method Body The method header is followed by the method body public static int countCharInWord (char ch, String word) { int count = 0; for (int i = 0; i<word.length(); i++) { if (word.charAt(i) == ch) { count++; } return count; } The return expression must be consistent with the return type ch and word are local data They are created each time the method is called, and are destroyed when it finishes executing

Example: Largest.java Read a sequence of numbers Print the max

Parameters Each time a method is called, the actual parameters in the call are copied into the formal parameters int num = countCharInWord ('e', "Heels"); { int count = 0; for (int i = 0; i<word.length(); i++) { if (word.charAt(i) == ch) { count++; } return count; } public static int countCharInWord (char ch, String word)

printStars (35); printStars (30 + 5); int num = 35; printStars (num); Parameters Formal parameters –variable declarations in the method header –automatic local variables for the method Actual parameters –actual values that are passed to the method –can be variables, literals, or expressions

Parameters Primitive Data Type Variables If a formal parameter is a variable of a primitive data type, can it be modified inside a method? –The value from the actual parameter is copied –There is no connection between variables inside the method and outside –Conclusion: it cannot be modified!!

Example: Largest.java Modify the values inside the comparison method

Parameters Reference Variables If a formal parameter is a reference variable, can the object be modified inside a method? –The address from the actual parameter is copied –The local reference variable points to the same object –Conclusion: it can be modified!!

Primitive Data Types What if we want to modify a variable of a primitive data type inside a method? –Encapsulate it in a class –Example: IntClass (ch. 6, p. 306) IntClass is a class suggested in the book, but it is not a built-in class in Java!!!

Data Scope The scope of data is the area in a program in which that data can be used (referenced) Data declared at the class level can be used by all methods in that class Data declared within a method can be used only in that method –also called local data Key to determining scope is to look for blocks of code (surrounded by { } ) –variables declared inside { } cannot be used outside –recall the problems some had with variables declared inside if statements

Data Scope Example public class Rectangle { // variables declared here are class-level // available in all methods in Rectangle class public int computeArea() { // variables declared here are method-level // only available in computeArea() } public void print() { // variables declared here are method-level // only available in print() }

Overloading Methods Overloading - the process of using the same method name for multiple methods The signature of each overloaded method must be unique –number of parameters –type of the parameters –not the return type of the method, though The compiler determines which version of the method is being invoked by analyzing the parameters

Overloading Methods public static double tryMe (int x) { return x +.375; } Version 1 public static double tryMe (int x, float y) { return x*y; } Version 2 Invocation result = tryMe (25, 4.32)

Overloaded Methods println Example The println method is overloaded: println (String s) println (int i) println (double d) and so on... The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total);

Example: PrintStars.java

To do Tomorrow: practice for mid-term –Bring laptops –Collect questions Pick examples that we have done so far and convert parts of the code to methods –Binary.java (homework 2) –AverageKeyboard.java –AsteriskPattern.java –…