Unformatted text preview:

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 methodsA method is a named group of declarations and statementsIf a method is in the same class, you execute those declarations and statements by calling the methodIf the method belongs to some other object, you execute it by sending a message to that objectWhen 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 methodInside 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 methodIn 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 separatelyMethods can use other methods, but should not depend on the “inner workings” of those other methods--just what they do, not how they do itMethods allow you to give names to parts of your computation, thus making your program more readableReadability is essential in good programmingProper choice of method names is importantVerbs 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 placeThis is an application of the DRY principle (“Don’t Repeat Yourself”)Methods are very good for putting code in only one placeDefining a methodA method has the syntax: access return-type method-name(parameters) { method-variables code} The access (public, protected, or private) is optionalExample: 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 methodIf 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 methodThe keyword void is used to indicate that a method doesn’t return a valueThe return statement must not specify a valueExample: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 statementReach the closing brace of the methodInstance variablesA variable declared within a class (but not within a method) is an instance variableEvery object (“instance”) of that class has its own variable with that nameExample: Every CokeMachine has its own amountEnteredInstance variables are “visible”--available for use--everywhere within the class in which they are definedInstance variables should almost always be marked private, so that other classes cannot “see” themExample: You don’t want a Customer object to be able to change the amountEntered in a CokeMachine without inserting coinsEvery instance variable should say something meaningful about its objectScope of variablesParameters to a method are visible throughout the methodParameters are discarded when the method returnsVariables declared within a block (between { and }) are visible from where they are declared up to the end of the blockThese variables are discarded when the block is exitedExample: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 methodsJava 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 objectsMost methods you write should not, and will not be staticEvery Java program has a public static void main(String[ ] args)methodThis 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 staticclass 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 methodJavadoc comments start with /** and end with */, and are put immediately before the methodThe 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 providesYou don’t need to mention the parameter type—Javadoc knows thatIf any instance variables are used, their use should be describedReferences to the object should be with “this”– this Tree, this JPanel, etc.@return descriptionA 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 thrownHTML markup may be used within the Javadoc commentTo generate the actual documentation from the comments (in Eclipse), do: Project  Generate Javadoc...Example Javadoc documentationpublic class Pair {


View Full Document

Penn CIT 590 - Methods

Download Methods
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Methods and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Methods 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?