Download presentation
Presentation is loading. Please wait.
Published byEunice Robertson Modified over 8 years ago
1
Methods CSC 171 FALL 2001 LECTURE 3
2
History The abacus
3
History The Father of Computing 1822 - Charles Babbage The Difference Engine First Government grant Babbage’s ideas were not widley accepted because of poor documentation
4
Methods Variables describe static aspects – “nouns” Methods describe dynamic aspects – “verbs”, “behaviors” – Methods “do things”
5
Methods We have seen some assignment statements where we do the computation in the program – int x = a + 5; – String b = “Hello” + “ “ + “World\n”;
6
Methods We have also had some occasion to use methods that do computation “elsewhere” – double d1 = Math.sqrt(50.9);
7
Methods Think of a method as a “black box” – We put something in – We get something out Putting something in – parameters Getting something out – Return values
8
Black Box Math sqrt() 3.0 9.0 double x = Math.sqrt(9.0);
9
A Computer Program public class myFirstProg { public static void main(String args[]){ System.out.println(“Hello, CSC171”); }
10
Black Box MyFirstProg main() void String args[] “side effects”
11
A Computer Program public class mySecondProg { public static void main(String args[]){ int x = 5, y = 8; int product = mymult(x,y); System.out.println( x + “ * “ + y + “ is “ + product); } public static int mymult(int n1, int n2){ return n1 * n2; }
12
Black Box MyFirstProg main() void String args[] mymult()
13
Sequence of events main() mymult() System.out.println() 5,8 40 “5 * 8 is 40” void
14
Proceedural Abstraction We define the input and output behavior – Contract We embed some complex behavior in a method. We refer to the method by a name We can write & debug the method once & then use it whenever we want.
15
public class myThirdProg { public static void main(String args[]){ int x = 5, y = 8; int product = mymult(x,y); System.out.println( x + “^3 * “ + y + “ is “ + product); } public static int mymult(int n1, int n2){ return mycube(n1) * n2; } public static int mycube(int x){ return x * x * x; } }
16
Sequence of events main() mymult() System.out.println() 5,8 1000 “5^3 * 8 is 1000” void mycube() 5 125
17
Interfaces – needed for project Interfaces are ways of “writing contracts” – Client communicates the input & output requirements Method names Parameters for each method Return types for each method
18
Interface definition public interface myMinMax { public int myMin(int x, int y); // no body public int myMax(int x, int y); // no body }
19
Interface use public class myProject implements myMinMax { public int myMin(int x, int y) { if (x < y) return x ; else return y; } public int myMax(int x, int y){ if (x>y) return x; else return y; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.