CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.

Slides:



Advertisements
Similar presentations
Procedural programming in Java
Advertisements

1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
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.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
CSCI 1100/1202 April 3, Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process.
Chapter 4: Writing Classes
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.
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
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
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.
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.
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.
COMP 110 Introduction to Programming Mr. Joshua Stough October 1, 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
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
COMP 14 Introduction to Programming Miguel A. Otaduy May 24, 2004.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
Introduction to Methods
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Writing Classes (Chapter 4)
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
CPS120: Introduction to Computer Science Functions.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 5.
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.
Introducing Objects and stuff GABY and MATT Definition: Object: “a class that is the root of the hierarchy tree for all classes in JAVA.” –An object.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
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
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Programming in Java (COP 2250) Lecture 10 Chengyong Yang Fall, 2005.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
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
Suppose we want to print out the word MISSISSIPPI in big letters.
Chapter 4: Writing Classes
Chapter 4: Writing Classes
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.
Starting Out with Java: From Control Structures through Objects
Chapter 4: Writing classes
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
Chapter 4 Writing Classes.
Chapter 6: User-Defined Functions I
Lecture 5- Classes, Objects and Methods
Presentation transcript:

CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009

Today in CSCI 51 Making your own methods –Procedural abstraction. Object-Oriented Design –Data abstraction

6 Fundamental Concepts of Programming Variables, and Assignment (data storage) Expressions, and Data Retrieval Conditional statements (making choices) Loops (repetition) Structured data, arrays (data abstraction) Functions (procedural abstraction)

What is a Method? Group of programming statements that we give a name Statements usually work together to perform a specific task/operation Every method belongs to a class

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

String Methods boolean equals(String str) int length() String toLowerCase() char charAt(int index) the result can be stored in a boolean variable or used in a boolean expression (return type) the method needs to be given another String (parameter) method name method specification, not syntax of use

Using String Methods list of String methods: Chapter 3 Steps: –create a String object –put data into the object –use the dot operator to "call" the method String line; line = keyboard.readLine(); String greeting = "Hello"; int len = line.length(); greeting = greeting.toUpperCase(); char ch = greeting.charAt(3);

Two Types of Methods Value-returning methods –"return", "evaluate to", "result in" some value –like mathematical functions –only returns a single value Void methods –performs operations but returns 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

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 * Only need to know 1-4 for predefined methods

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

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

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 argument A method declaration begins with a method header visibility modifiers

int number = countCharInWord ('e', "Heels"); 2 Return Type Indicates the type of value that the method evaluates to (or, sends back to the calling location) –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

Method Body The method header is followed by the method body { 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 public static int countCharInWord (char ch, String word)

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)

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.

Void Methods Does not return a value Has 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

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

Code Re-Use Methods can also be used to save typing If you have a section of code that does one task and it needs to be done multiple times, you can write it as a method Example: you want to print the following heading to start your program *********************************** ************ Blackjack ************ ***********************************

public class MyProgram { public static void main (String[] args) { printStars(); System.out.print ("************"); System.out.print (" Blackjack "); System.out.println ("************"); printStars(); } public static void printStars() { System.out.print ("***************"); System.out.println ("*****"); }

printStars What if we wanted to change the number of stars printed on the line? give the number of stars as a parameter

public class MyProgram { public static void main (String[] args) { printStars(35); System.out.print ("************"); System.out.print (" Blackjack "); System.out.println ("************"); printStars(35); } public static void printStars(int numStars) { for (int i = 0; i<numStars; i++) { System.out.print ("*"); } System.out.println(); }

printStars What if we wanted to change the character printed (something besides stars?) change the name of the method (because it may not print stars) --> printChars give the character as a parameter

public class MyProgram { public static void main (String[] args) { printChars(35, '#'); System.out.print ("###############"); System.out.print (" Blackjack "); System.out.println ("###############"); printChars(35, '#'); } public static void printChars(int num, char ch) { for (int i = 0; i<num; i++) { System.out.print (ch); } System.out.println(); }

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

Object-Oriented Design What is it? Designing a solution to a problem by first identifying components called objects, and determining how the objects interact with each other

Objects VCR Example Use it without knowing how it's made Internal parts are hidden -- only interact with the provided buttons Can't modify the functions of a VCR -- record button always records, play button always plays Same is true for with objects (like strings) that are provided by Java

Objects Consists of data and operations on the data Data - descriptive characteristics Operations - what it can do (or what can be done to it) Example A coin that can be flipped so that its face shows either "heads" or "tails" –data: its current face (heads or tails) –operations: it can be flipped Operations can change data.

Objects And Methods and Classes We represent operations with methods –group of statements that are given a name We can use objects and their methods without knowing exactly how the methods work An object is an instance of a class. A class is the blueprint of an object. –the class provides the methods that can operate on an object of that class

Classes A class contains data declarations and method declarations A class is a description of an object –just a model, not an actual object –you can think of the concept of a book without thinking of a particular book A class is no more an object than a blueprint is an actual house

Object-Oriented Design Simplified Methodology 1. Write down detailed description of problem 2. Identify all (relevant) nouns and verbs 3. From list of nouns, select objects 4. Identify data components of each object 5. From list of verbs, select operation

Object-Oriented Design Example 1 Problem Statement –Write a program to input the length and width of a rectangle and calculate and print the perimeter and area of the rectangle

Example 1 Building a Rectangle Identify nouns –length, width, rectangle, perimeter, area Identify each class –length of a rectangle –width of a rectangle –perimeter of a rectangle –area of a rectangle

Example 1 Building a Rectangle Identify data members for each class –nouns: length, width, area, perimeter –what are the essential nouns for describing the rectangle? –area and perimeter can be computed if we know the length and width

Example 1 Building a Rectangle Identify operations for each class –input, calculate, print –setLength –setWidth –computePerimeter –computeArea –print –getLength –getWidth directly from problem statement customary to include operations to get the value of the data members

class Rectangle Data Members and Operations Last Step: design and implement an algorithm for each operation class name data members operations (methods)

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

` Rectangle A class (the concept) length = 15, width = 3 An object (the realization) length = 20, width = 6 length = 15, width = 15 Multiple objects from the same class

Non-Concrete Objects Objects in programs don't always have real-world analogs Example object: error message data: text of the error message operation: print the text of the error message to the screen