Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Alice in Action with Java
Static Methods Chapter 4. Chapter Contents Objectives 4.1 Introductory Example: Old MacDonald Had a Farm … 4.2 Getting Started with Methods 4.3 Example:
Chapter 6: User-Defined Functions I
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
Computer Programming 1 Functions. Computer Programming 2 Objectives Take a first look at building functions Study how a function is called Investigate.
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.
Computer Programming 1 Problem Solving and Software Engineering.
Classes with multiple methods Part 1. Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs.
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
Defining Classes and Methods Chapter 4.1. Key Features of Objects An object has identity (it acts as a single whole). An object has state (it has various.
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Introduction to Methods
Basic Elements of C++ Chapter 2.
1 4.3 Example: Volume of a Sphere Given the radius r, what is the weight of a ball (sphere) of wound twine?Given the radius r, what is the weight of a.
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.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6: User-Defined Functions
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
CPS120: Introduction to Computer Science Functions.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
1 Simple Methods Chap. 4 Study Sections 4.1 – 4.4 Writing Reusable Formulas.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Methods: A Deeper Look. Template for Class Definition public class { } A.Import Statement B.Class Comments C.Class Name D.Data members E.Methods (inc.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
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.
Simple Functions Writing Reuseable Formulas. Problem Using OCD, design and implement a program that computes the area and circumference of an Australian.
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.
Lecture 5 functions 1 © by Pearson Education, Inc. All Rights Reserved.
1 Simple Methods Chap. 4 Study Sections 4.1 – 4.4 Writing Reusable Formulas.
Chapter 3: User-Defined Functions I
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Methods CSCI 1301 What is a method? A method is a collection of statements that performs a specific task. Pre-Defined methods: available in Java library.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
1 UMBC CMSC 104, Section Fall 2002 Functions, Part 1 of 3 Topics Top-down Design The Function Concept Using Predefined Functions Programmer-Defined.
CS305j Introduction to Computing Parameters and Methods 1 Topic 8 Parameters and Methods "We're flooding people with information. We need to feed it through.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
More About Objects and Methods
Chapter Topics The Basics of a C++ Program Data Types
Chapter 7 User-Defined Methods.
Chapter 6: User-Defined Functions I
Methods Chapter 6.
Basic Elements of C++.
Writing Reuseable Formulas
User-Defined Functions
Basic Elements of C++ Chapter 2.
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
A First Book of ANSI C Fourth Edition
Chapter 6: User-Defined Functions I
Methods/Functions.
Corresponds with Chapter 5
Presentation transcript:

Static Methods

2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference and primitive parameter passing Compare design process for methods to program design Give an example of Swing class JApplet used as a container in building applets.

3 Motivation We seek to write reusable code for the purpose of avoiding having to do the same task repeatedly This can be done by putting the code in a method Various objects in a program can invoke the same method This chapter gives us the means to write Java methods

4 Java Method Definition Syntax: modifiers returnType methodName (parameterDeclaration) { statements } modifiers : describers (public, private, etc.) returnType : type of value returned by method, or void if it does not return a value methodName : identifier that names the method parameterDeclaration : list of parameters, separated by commas statements : define the behavior of the method

5 Methods Heading of the method includes: modifiers return type name parentheses with parameters Return statement – syntax: return expression expression is evaluated method terminates execution transferred to caller value of expression returned as value computed by the method

6 Methods That Return Nothing Type void is specified Example public static void main (String [ ] args) { statements } No return statement is required These methods can be thought of as "doing a task", instead of returning a value

7 Designing and Defining Methods Note the usefulness of object- centered design Similar to design of programs They have objects, behavior, and use an algorithm

8 Method Specifications Give a description of what the method is supposed to do 1. What values does the method receive? 2. What values are input to the method? 3. What are the restrictions or limitations the preconditions? 4. What values does the method return? 5. What values does the method output 6. What effects are produced, the postconditions?

9 Method Specifications for Mass-to-Energy For our Mass-to-Energy method: 1. Receive: mass, a double 2. Precondition: mass > 0 3. Return: the amount of energy when mass is converted to energy Mass-to-Energy method energy

10 Method Stubs Stub includes: Heading Empty braces { } for body Heading includes: Name Parameter for each argument received must be specified Return type (or void) public static double massToEnergy (double m) { }

11 Local Variables Other constant values or temporary variables Named values not received from the caller They exist only while the method is executing Another method may use same identifier The local variable/constant can be accessed only from within the method where declared Compiler will catch this error

12 Method Algorithm After stub is defined return to design phase specify operations establish algorithm Algorithm for Mass-to-Energy Receive mass m from caller Return

13 Method for Mass-To-Energy public static double massToEnergy(double m) { final double C = e8; // meters per sec return m * Math.pow(C,2); } Specification determines the heading Algorithm determines form of body

14 Method Documentation Include a /* comment */ at the top to give the method's specification what it does Parameters Receive: Description of value return Return:

15 Flow of Execution Statements in main() executed Method call encountered Control passes to method values passed to parameters statements in method executed return encountered Control passes back to statement following method call

16 Method Testing: Verification and Validation Often test a method independently of program that uses it Write simple "driver" program receive inputs invoke method print results Observe correctness of results

17 Parameter Passing When a method called list of arguments in call matched (L-> R) with parameters must be same number of parameters types must be compatible Values in call copied to parameters In examples shown so far, argument in call cannot be altered by action of method method x

18 Parameter Passing In Java arguments are passed by value When argument is primitive type argument in call cannot be changed When argument is reference type Method cannot change the object reference Method can invoke object methods and modify accessible variables within the object

19 Parameter Passing Consider int r=-1; b=-1; g=-1; pen.getRGBColor (r,g,b); This will not act as you may wish r, g, and b will not be changed The values get passed one way only

20 Parameter Passing Instead specify class RGBColor { public int red, green, blue; } class Pen { int redValue, greenValue, blueValue; void getRGBCoor (RGBColor aColor) { aColor.red = redValue; aColor.green = greenValue; aColor.blue = blueValue; } }

21 Parameter Passing Then specify RGBColor penColor = new RGBColor; pen.getRGBColor (penColor); Now penColor is an object The method invokes object call penColor is indeed changed Generally speaking, it is easier to write classes with methods that return a value.

22 Object-Centered Design with Methods Behavior state precise behavior of program Objects identify problem's objects build a new class to represent types as necessary

23 Object-Centered Design with Methods Operations identify required operations – if operation not predefined … build methods to implement the operation store method in class responsible for providing the operation Algorithm arrange operations in an order that solves the problem

24 Example: Volume of a Sphere Given the radius r, what is the weight of a ball (sphere) of wound twine? Object-Centered Design display prompt for radius read value for radius compute weight of sphere display results on screen Note this is generalized for sphere of arbitrary size

25 Operations Display a String (prompt) on the screen Read a number from keyboard, store it in radius Compute weight using radius Display a number ( weight ) on screen

26 New Class Required Java has no predefined sphere object Also no predefined operation for volume or weight of a sphere Solution: build a method to calculate weight create a sphere class to use the weight method We will need an additional variable object density (weight = density * volume)

27 A Volume Method Objects Volume = (4/3) * Pi * r 3 Note r is the only variable 4, 3, and Pi are constants These (along with the result, volume) are the objects of this method

28 Volume Method Operations and Algorithm Receive real value ( radius ) from caller Cube the real value ( radius 3 ) Multiply by 4.0 and by Pi Divide by 3.0 Return result 4.0 * Pi * radius 3 /3.0

29 Defining Class and Method class Sphere extends Object { public static double volume (double radius) { return 4.0 * Math.PI * Math.pow (radius, 3)/3.0; } Public : other classes can access Static: main methods can use it without creating a Sphere object Double: returns a real value Named volume: accurately describes and documents purpose of method

30 Mass Method mass = density * volume(radius) density and radius are the inputs to the method volume is a call to the volume method mass is the result to be returned These are the objects of the method

31 Mass Algorithm Receive inputs radius density Multiply density times value returned by call to volume method Return these results

32 Defining the Density Method class Sphere extends Object { public static double volume (double radius) {... } public static double density (double, radius, double density) { return density * volume(radius); }

33 Algorithm for Main Method Construct theKeyboard, theScreen theScreen displays prompt for radius theKeyboard reads double value into radius theScreen displays prompt for density theKeyboard reads a double into density Compute weight, use mass() method from class Sphere theScreen displays weight and descriptive text

34 Methods: A Summary Specify a parameter for each value received by the method Value supplied to the parameter when method invoked is called an argument Arguments matched with parameters from left to right must be same number of arguments types must match (be compatible)

35 Methods: A Summary If argument is a reference type, address is copied to parameter both parameter and argument refer to same object Instance (object) methods defined without the static modifier messages invoking them are sent to an instance of the class When method1() calls method2(), control returns to method1() when method2() finishes

36 Methods: A Summary Local objects are defined only while method containing them is executing void is use to specify return type of a method which returns no values Value is returned from a method to the call using the return statement