Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 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

2 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

3 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();

4 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 + "%"); }

5 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;

6 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

7 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) { } }

8 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

9 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

10 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

11 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

12 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));

13 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

14 Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 14 The Math Class Includes constants Math.PI (approximately 3.14159) 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

15 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.

16 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

17 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.

18 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

19 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

20 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


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

Similar presentations


Ads by Google