Methods CSC 171 FALL 2001 LECTURE 3
History The abacus
History The Father of Computing Charles Babbage The Difference Engine First Government grant Babbage’s ideas were not widley accepted because of poor documentation
Methods Variables describe static aspects – “nouns” Methods describe dynamic aspects – “verbs”, “behaviors” – Methods “do things”
Methods We have seen some assignment statements where we do the computation in the program – int x = a + 5; – String b = “Hello” + “ “ + “World\n”;
Methods We have also had some occasion to use methods that do computation “elsewhere” – double d1 = Math.sqrt(50.9);
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
Black Box Math sqrt() double x = Math.sqrt(9.0);
A Computer Program public class myFirstProg { public static void main(String args[]){ System.out.println(“Hello, CSC171”); }
Black Box MyFirstProg main() void String args[] “side effects”
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; }
Black Box MyFirstProg main() void String args[] mymult()
Sequence of events main() mymult() System.out.println() 5,8 40 “5 * 8 is 40” void
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.
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; } }
Sequence of events main() mymult() System.out.println() 5, “5^3 * 8 is 1000” void mycube() 5 125
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
Interface definition public interface myMinMax { public int myMin(int x, int y); // no body public int myMax(int x, int y); // no body }
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; }