Method. Why Write Methods? Overview. CS256 Computer Science I Kevin Sahr, PhD. Lecture 21: Writing Class Methods. ClassName.methodName(arguments)

Similar documents
Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

Class API. Class API. Constructors. CS200: Computer Science I. Module 19 More Objects

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

CS111: PROGRAMMING LANGUAGE II

Lecture 5: Methods CS2301

CS313D: ADVANCED PROGRAMMING LANGUAGE

Chapter 4 Defining Classes I

CS-201 Introduction to Programming with Java

CS1150 Principles of Computer Science Methods

Flow of Control. Conditional Statements. Conditional Statements. CS256 Computer Science I Kevin Sahr, PhD. Lecture 15: The If-Statement

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CS111: PROGRAMMING LANGUAGE II

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

CS1150 Principles of Computer Science Methods

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

More Data Types. The Char Data Type. Variable Declaration. CS200: Computer Science I. Module 14 More Data Types

CS159. Nathan Sprague

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Handout 7. Defining Classes part 1. Instance variables and instance methods.

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Computing Science 114 Solutions to Midterm Examination Tuesday October 19, In Questions 1 20, Circle EXACTLY ONE choice as the best answer

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

(Not Quite) Minijava

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Review questions. Review questions, cont d. Class Definition. Methods. Class definition: methods. April 1,

Introduction. C provides two styles of flow control:

CS-201 Introduction to Programming with Java

Object-Oriented Design Lecture 14 CSU 370 Fall 2007 (Pucella) Friday, Nov 2, 2007

Comparing Data. Comparing Floating Point Values. Comparing Float Values. CS257 Computer Science I Kevin Sahr, PhD

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Computer Science II (20082) Week 1: Review and Inheritance

Methods. CSE 114, Computer Science 1 Stony Brook University

CSE 230 Intermediate Programming in C and C++ Functions

CT 229 Fundamentals of Java Syntax

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Project Compiler. CS031 TA Help Session November 28, 2011

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

COE318 Lecture Notes Week 10 (Nov 7, 2011)

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Computational Expression

CS11 Java. Fall Lecture 1

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Chapter 3 Function Overloading

COP4020 Programming Assignment 1 - Spring 2011

CS110D: PROGRAMMING LANGUAGE I

Prelim One Solution. CS211 Fall Name. NetID

Lecture Set 4: More About Methods and More About Operators

AP CS Unit 3: Control Structures Notes

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

Standard Version of Starting Out with C++, 4th Edition. Chapter 6 Functions. Copyright 2003 Scott/Jones Publishing

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Lecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Lecture 13. Notation. The rules. Evaluation Rules So Far

CS 6353 Compiler Construction Project Assignments

( &% class MyClass { }

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

M e t h o d s a n d P a r a m e t e r s

LECTURE 06 FUNCTIONS

CS 231 Data Structures and Algorithms, Fall 2016

Final Exam COMP Fall 2004 Dec 16, 2004

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

4. C++ functions. 1. Library Function 2. User-defined Function

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

ECE 122. Engineering Problem Solving with Java

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

CS 139 Practice Midterm Questions #2

PROGRAMMING FUNDAMENTALS

CS 11 java track: lecture 1

COMP 250 Winter 2011 Reading: Java background January 5, 2011

APCS Semester #1 Final Exam Practice Problems

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

Computer Programming: C++

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

Programming Language. Functions. Eng. Anis Nazer First Semester

Lecture Set 4: More About Methods and More About Operators

1 Lexical Considerations

CS110: PROGRAMMING LANGUAGE I

2. Functions I: Passing by Value

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Chapter 6: Functions

Lecture 10 Declarations and Scope

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Chapter 4: Writing Classes

Lab5. Wooseok Kim

Chapter 6 Introduction to Defining Classes

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

An introduction to Java II

FORM 2 (Please put your name and form # on the scantron!!!!)

Selected Questions from by Nageshwara Rao

Transcription:

CS256 Computer Science I Kevin Sahr, PhD Lecture 21: Writing Class Methods 1 Method a method is a set of program statements that can be executed as a unit the statements are executed by invoking the method 2 Why Write Methods? methods allow us to hide the details of a set of statements (an example of abstraction) methods allow us to write a complicated set of statements once, and then execute them multiple times in our programs EX: say we had a method that gets and returns a validated positive number; we could invoke it whenever our program needs to input a positive number 3 Overview every method must be defined within a class methods can be defined in a different class than the main method (EX: Input and Output classes) class methods are invoked using the syntax: ClassName.methodName(arguments) 4

Single Class methods can also be defined in the same class as the main method a method can be invoked from methods in the same class (including the main method) using the syntax: methodname(arguments) current class name is assumed 5 Method Parts Method Header Output.showMessage("Hello world!"); Method Body Statement(s) 6 EX: Class with 2 Class Methods Method Header Method Body public class Simple public static void methoda () Output.showMessage("In methoda"); } // method methoda Output.showMessage("Before methoda"); methoda(); Output.showMessage("After methoda"); } // class Simple 7 EX: Method Invocation 3 public class Simple public static void methoda () Output.showMessage("In methoda"); } // method methoda 1 2 4 Output.showMessage("Before methoda"); methoda(); Output.showMessage("After methoda"); } // class Simple 8

Statements the method body can contain any valid statements EX: variable declarations conditional statements while-loops invocations of other methods etc. 9 Variable Scope the area in a program where a variable is visible is known as the scope of the variable variables may only be used in parts of the program within the variable s scope 10 Local Variables variables declared within a method body are local variables local variables can only be used within the method where they are declared local variables cease to exist when the method they are declared in exits methods cannot see local variables declared in other methods variables with the same name but declared inside different methods are entirely different variables 11 Local Variables public class LocVar public static void somemethod () int num; num = 5; } // method somemethod different variables int num; num = 0; somemethod(); Output.showValue("num is" ", num); } // class LocVar 12

Information In & Out of Method when your program invokes a method it can pass data into, and get data out of, the method pass data into the method via arguments get data out of the method via the method return value 13 Arguments arguments act exactly like local variables except that they are: declared as formal arguments in the argument list in the method header initialized with the corresponding actual argument values when the method is invoked 14 EX: Passing Arguments public class Args public static void adder (String label, int a, int b) int sum; sum = a + b; Output.showValue(label, sum); } // method adder int num = 5; adder("the total is: ", 10, num); Output.showMessage("After adder."); 15 Return Value a method can return a single value to the invoking program requires two things: appropriate return type in the method header a return statement in the method body that returns a value of the appropriate return type 16

Return Statement syntax: return expression; return is a Java keyword when executed, immediately exits the method returns the value of expression to the invoking program expression must have a data type that is compatible with the return type of the method 17 EX: Returning a Value public class Return public static double product (double x, double y) double result; result = x * y; return result; } // method product double p; p = product(6.5, 2.0); Output.showValue("p is ", p); } // class Return 18 EX: Multiple Methods Problem: output the secret ingredient of Tasti-Chips abstract pseudocode: confirm user agrees to terms display the secret ingredient confirm user agrees to terms 19 The Methods each step could be very complex let s create 2 methods named: confirmagreement displaysecret these will only perform output no arguments or return values needed 20

Method confirmagreement Returns Nothing No Arguments public static void confirmagreement () String msg = "The secret ingredient is proprietary.\n"; msg = msg + "By choosing OK, you agree\n"; msg = msg + "to hold this information confidential."; Output.showMessage(msg); } // method confirmagreement 21 Method displaysecret public static void displaysecret () String msg = "The secret ingredient in Tasti-Chips ; msg = msg + is extra MSG."; Output.showMessage(msg); } // method displaysecret 22 Method main confirmagreement(); displaysecret(); confirmagreement(); Secret1.java contains all methods (including main) in a single class 23 Another Method let s make the user enter a pin number before letting them view the secret create a method to verify the user s pin: verifypin takes as an argument the correct integer pin gets user s pin from input returns whether or not the user entered the correct pin 24

Method verifypin public static boolean verifypin (int goodpin) int pin; boolean isgood; pin = Input.readInt("Enter your pin: "); if (pin == goodpin) isgood = true; else // bad pin isgood = false; return isgood; } // method verifypin 25 Method main int therightpin = 4444; if (verifypin(therightpin)) confirmagreement(); displaysecret(); confirmagreement(); } // if correct pin else Output.showMessage("INCORRECT PIN\n" + "Sorry, you cannot see the secret."); 26 Secret2.java contains all methods (including main) in a single class take a moment to look at, compile, and experiment with this program 27 Classes without a main Method methods can be defined in a class without a main method these methods can then be used by any application program EX: Output, Input, and Math classes such classes must be separately compiled these classes can not be separately executed no main method means they are not themselves applications the compiled.class file must be in the same directory with any application that invokes any of its methods 28

EX: Cylinder Class the Cylinder class provides methods for calculating the surface area and volume of a cylinder the Cylinder class API is available on the website the source code file Cylinder.java defines the methods given in the Cylinder class API the source code file CylTest.java contains an application that invokes Cylinder methods 29 EX: Cylinder Class (cont.) to run the example you must first: compile the class (Cylinder.java) place the compiled file (Cylinder.class) in the same directory with the application source code file (CylTest.java) compile the application (CylTest.java) spend some time looking at and experimenting with this example 30 Lecture 21 Vocabulary method variable scope local variable return statement 31