MethodsAbout methodsExample methodWhy methods?Defining a methodReturning a result from a methodReturning no result from a methodInstance variablesScope of variablesMethods and static methodsEscaping from staticDocumenting a methodExample Javadoc documentationThe EndJan 14, 2019MethodsAbout methodsA method is a named group of declarations and statementsIf a method is in the same class, you execute those declarations and statements by calling the methodIf the method belongs to some other object, you execute it by sending a message to that objectWhen you call the method, you can give it parameters (information, such as numbers, going into the method)A method typically has a return value (a single piece of information coming out of the method)Declarationsand statementsparameterparameterparameterreturn valueExample methodInside a CokeMachine class, you might have this method:public void insertCoin(int coin) { // “coin” is a parameter if (coin == 5 || coin == 10 || coin == 25) { amountEntered = amountEntered + coin; }}Inside the CokeMachine class, you might have code like this:int dime = 10;insertCoin(dime); // this is a call to the insertCoin methodIn some other class, you might have code like this:CokeMachine cheater = new CokeMachine(); CokeMachine honestAbe = new CokeMachine(); int dime = 10;honestAbe.insertCoin(dime); // this is a message to honestAbeWhy methods?Methods help you break up a complex problem into simpler subproblems, which you can solve separatelyMethods can use other methods, but should not depend on the “inner workings” of those other methods--just what they do, not how they do itMethods allow you to give names to parts of your computation, thus making your program more readableReadability is essential in good programmingProper choice of method names is importantVerbs are usually best, since methods “do something”If you have anything the least bit complicated to compute, you should write (and debug) it in only one placeThis is an application of the DRY principle (“Don’t Repeat Yourself”)Methods are very good for putting code in only one placeDefining a methodA method has the syntax: access return-type method-name(parameters) { method-variables code} The access (public, protected, or private) is optionalExample: private boolean isAdult(int age) { int magicAge = 21; return age >= magicAge;}Example: double average(int a, int b) { return (a + b) / 2.0;}Returning a result from a methodIf a method is to return a result, it must specify the type of the result:boolean isAdult ( …You must use a return statement to exit the method with a result of the correct type:return age >= magicAge;Returning no result from a methodThe keyword void is used to indicate that a method doesn’t return a valueThe return statement must not specify a valueExample:void printAge(String name, int age) { System.out.println(name + " is " + age + " years old."); return;}There are two ways to return from a void method:Execute a return statementReach the closing brace of the methodInstance variablesA variable declared within a class (but not within a method) is an instance variableEvery object (“instance”) of that class has its own variable with that nameExample: Every CokeMachine has its own amountEnteredInstance variables are “visible”--available for use--everywhere within the class in which they are definedInstance variables should almost always be marked private, so that other classes cannot “see” themExample: You don’t want a Customer object to be able to change the amountEntered in a CokeMachine without inserting coinsEvery instance variable should say something meaningful about its objectScope of variablesParameters to a method are visible throughout the methodParameters are discarded when the method returnsVariables declared within a block (between { and }) are visible from where they are declared up to the end of the blockThese variables are discarded when the block is exitedExample:public double average(double x, double y, double z) { // x, y, and z are visible throughout this method double count = 3.0; // count is visible from here forward double avg = (x + y + z) / count; // avg is visible from here forward return avg; // the v alue of avg is returned, but the variable itself, // and the variable count, are discarded}Note that count and avg could be instance variables, but since they don’t say anything about the object they are in, this would be very poor styleMethods and static methodsJava has two kinds of methods: static methods and non-static methods (also know as instance methods) However, before we can talk about what it means to be static, we have to learn a lot more about classes and objectsMost methods you write should not, and will not be staticEvery Java program has a public static void main(String[ ] args)methodThis starts us in a “static context”To “escape from static”, I recommend starting every program in a certain way, as shown on the next slideEscaping from staticclass MyClass { public static void main(String[] args) { new MyClass().run(); } void run() { // Your real code begins here }}You can replace the names MyClass and run with names of your choice, but notice that each name occurs in two places, and they have to match upDocumenting a methodJavadoc comments start with /** and end with */, and are put immediately before the methodThe text is written as if the method description began with the words “This method...”The comment ends with the following tags:@param name description (one for each parameter)The description tells what information the named parameter providesYou don’t need to mention the parameter type—Javadoc knows thatIf any instance variables are used, their use should be describedReferences to the object should be with “this”– this Tree, this JPanel, etc.@return descriptionA description of the value that is returned (omit if void)@throws exception cause (one for each Exception)Tells what condition will cause this Exception to be thrownHTML markup may be used within the Javadoc commentTo generate the actual documentation from the comments (in Eclipse), do: Project Generate Javadoc...Example Javadoc documentationpublic class Pair {
View Full Document