Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.

Slides:



Advertisements
Similar presentations
Introduction to Programming G51PRG University of Nottingham Revision 3 Essam Eliwa.
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.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference l Parameter passing Classes, Objects, and Methods.
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 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Classes, Objects, and Methods
Copywrite 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used.
More About Objects and Methods
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
1 Chapter 5 Methods. 2 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
HST 952 Computing for Biomedical Scientists Lecture 5.
Classes, Objects, and Methods
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
More About Objects and Methods Chapter 5. When an Object Is Required Methods called outside the object definition require an object to precede the method.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Lecturer: Dr. AJ Bieszczad Chapter 5 COMP 150: Introduction to Object-Oriented Programming 5-1 l Programming with Methods l Static Methods and Static Variables.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
COMP 150: Introduction to Object-Oriented Programming Lecturer: Dr. AJ Bieszczad 4-1 Chapter 4 l Class and Method Definitions l Information Hiding and.
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.
Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void.
1 Week 8 l Methods l Parameter passing Methods. 2 Using Methods l Methods are actions that an object can perform. l To use a method you invoke or call.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Polymorphism l Constructors.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
Classes - Intermediate
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Methods.
CPSC 233 Tutorial 5 February 9 th /10 th, Java Classes Each Java class contains a set of instance variables and methods Instance Variables: Type.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
More About Objects and Methods
Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Functions II
Static and non-Static Chapter 5.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Classes, Objects, and Methods
Defining Classes and Methods
Chapter 6 Methods: A Deeper Look
Group Status Project Status.
Chapter 6 Methods.
Chapter 5 Methods.
Object Oriented Programming in java
Defining Classes and Methods
Defining Classes and Methods
Classes, Objects and Methods
More About Objects and Methods Chapter 5 Programming with Methods
Corresponds with Chapter 5
More About Objects and Methods Chapter 5 Programming with Methods
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference l Parameter passing Classes, Objects, and Methods

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 2 Using Methods l Methods are actions that an object can perform. l To use a method you invoke or call it. Example of a method call: speciesOfTheMonth.writeOutput() l Two basic kinds of methods: »methods that return a single value »void methods that do some action other than returning a value calling object— tells which object will do the action method name—tells which action the object will perform parameter list in parentheses—parameters give info to the method, but in this example there are no parameters

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 3 Return Type of Methods l All methods require that the return type be specified l Return types may be: »a primitive data type, such as char, int, double, etc. »a class, such as String, SpeciesFirstTry, etc. »void if no value is returned You can use a method anyplace where it is legal to use its return type, for example the readLineInt() method of SavitchIn returns an integer, so this is legal: int next = SavitchIn.readLineInt();

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 4 void Method Example The definition of the writeOutput method of SpeciesFirstTry : Assuming instance variables name, population, and growthRate have been defined and assigned values, this method performs an action (writes values to the screen) but does not return a value public void writeOutput() { System.out.println("Name = " + name); System.out.println("Population = " + population); System.out.println("Growth = " + growthRate + "%"); }

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 5 Return Statement Methods that return a value must execute a return statement that includes the value to return l For example: public int getCount() { return count; } public int count = 0;

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 6 Method and Class Naming Conventions Good Programming Practice l Use verbs to name void methods »they perform an action l Use nouns to name methods that return a value »they create (return) a piece of data, a thing l Start class names with a capital letter l Start method names with a lower case letter

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 7 The main Method A program written to solve a problem (rather than define an object) is written as a class with one method, main Invoking the class name invokes the main method See the text: SpeciesFirstTryDemo l Note the basic structure: public class SpeciesFirstTryDemo { public static void main(String[] args) { } }

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 8 Local Variables and Blocks l A block (a compound statement) is the set of statements between a pair of matching braces (curly brackets) l A variable declared inside a block is known only inside that block »it is local to the block, therefor it is called a local variable »when the block finishes executing, local variables disappear »references to it outside the block cause a compile error

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 9 Local Variables and Blocks l Some programming languages (e.g. C and C++) allow the variable name to be reused outside the local block »it is confusing and not recommended, nevertheless, it is allowed l However, a variable name in Java can be declared only once for a method »although the variable does not exist outside the block, other blocks in the same method cannot reuse the variable's name

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 10 When and Where to Declare Variables l Declaring variables outside all blocks but within the method definition makes them available within all the blocks Good programming Practice: l declare variables just before you use them l initialize variables when you declare them l do not declare variables inside loops »it takes time during execution to create and destroy variables, so it is better to do it just once for loops) it is ok to declare loop counters in the Initialization field of for loops, e.g. for(int i=0; i <10; i++)… »the Initialization field executes only once, when the for loop is first entered

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 11 Passing Values to a Method: Parameters l Some methods can be more flexible (therefor useful) if we pass them input values l Input values for methods are called passed values or parameters l Parameters and their data types must be specified inside the parentheses of the heading in the method definition »these are called formal parameters l The calling object must put values of the same data type, in the same order, inside the parentheses of the method invocation »these are called arguments, or actual parameters

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 12 Parameter Passing Example l What is the formal parameter in the method definition? »numberIn l What is the argument in the method invocation? »next //Definition of method to double an integer public int doubleValue(int numberIn) { return 2 * numberIn; } //Invocation of the method... somewhere in main int next = SavitchIn.readLineInt(); System.out.println("Twice next = " + doubleValue(next));

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 13 Pass-By-Value: Primitive Data Types as Parameters l When the method is called, the value of each argument is copied (assigned) to its corresponding formal parameter l The number of arguments must be the same as the number of formal parameters l The data types of the arguments must be the same as the formal parameters and in the same order l Formal parameters are initialized to the values passed l Formal parameters are local to their method l Variables used as arguments cannot be changed by the method »the method only gets a copy of the variable's value

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 14 The Math Class Includes constants Math.PI (approximately ) and Math.E (base of natural logarithms which is approximately 2.72) Includes three similar static methods: round, floor, and ceil »All three return whole numbers (although they are type double ) »Math.round returns the whole number nearest its argument Math.round(3.3) returns 3.0 and Math.round(3.7) returns 4.0 »Math.floor returns the nearest whole number that is equal to or less than its argument Math.floor(3.3) returns 3.0 and Math.floor(3.7) returns 3.0 »Math.ceil (short for ceiling) returns the nearest whole number that is equal to or greater than its argument Math.ceil(3.3) returns 4.0 and Math.ceil(3.7) returns 4.0

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 15 Designing Methods: Top-Down Design l In pseudocode, write a list of subtasks that the method must do. l If you can easily write Java statements for a subtask, you are finished with that subtask. l If you cannot easily write Java statements for a subtask, treat it as a new problem and break it up into a list of subtasks. l Eventually, all of the subtasks will be small enough to easily design and code. l Solutions to subtasks might be implemented as private helper methods. l Top-down design is also known as divide-and-conquer or stepwise refinement.

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 16 Programming Tips for Writing Methods Apply the principle of encapsulation and detail hiding by using the public and private modifiers judiciously »If the user will need the method, make it part of the interface by declaring it public »If the method is used only within the class definition (a helper method, then declare it private Create a main method with diagnostic (test) code within a class's definition »run just the class to execute the diagnostic program »when the class is used by another program the class's main is ignored

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 17 Testing a Method l Test programs are sometimes called driver programs l Keep it simple: test only one new method at a time »driver program should have only one untested method l If method A uses method B, there are two approaches: l Bottom up »test method B fully before testing A l Top down »test method A and use a stub for method B »A stub is a method that stands in for the final version and does little actual work. It usually does something as trivial as printing a message or returning a fixed value. The idea is to have it so simple you are nearly certain it will work.

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 18 Overloading l The same method name has more than one definition within the same class l Each definition must have a different signature »different argument types, a different number of arguments, or a different ordering of argument types »The return type is not part of the signature and cannot be used to distinguish between two methods with the same name and parameter types

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 19 Signature l the combination of method name and number and types of arguments, in order equals(Species) has a different signature than equals(String) »same method name, different argument types myMethod(1) has a different signature than myMethod(1, 2) »same method name, different number of arguments myMethod(10, 1.2) has a different signature than myMethod(1.2, 10) »same method name and number of arguments, but different order of argument types

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 20 Overloading and Argument Type l Accidentally using the wrong datatype as an argument can invoke a different method For example, see the Pet class in the text »set(int) sets the pet's age »set(double) sets the pet's weight »You want to set the pet's weight to 6 pounds: –set(6.0) works as you want because the argument is type double –set(6) will set the age to 6, not the weight, since the argument is type int