MethodsComplexityWhy objects?A fruity analogyWhy methods?Modeling behaviors: Example 1Modeling behaviors: Example 2Divide and conquer: Example 1Divide and conquer: Example 2When do you write a method?Kinds of methodsA common errorWhen to make a method staticExamples of static methodsDefining a methodInformation flowFormal parametersMethod variablesPrimitive parameters are copied inObjects are differentObject references are copied inAssignmentsSlide 23Using instance methods IUsing instance methods IIUsing instance methods IIIUsing class methods IUsing class methods IIVocabularyThe EndJan 13, 2019Methods2ComplexityThe programmer's biggest adversary is complexityThe programmer's biggest adversary is complexityPrimitive types and the basic statements Primitive types and the basic statements (assignment, (assignment, whilewhile, , ifif, etc.) are theoretically , etc.) are theoretically enough to perform any computationenough to perform any computationEverything else in Java is designed to organize Everything else in Java is designed to organize actions and data in order to control complexityactions and data in order to control complexityIn particular, we try to organize everything into In particular, we try to organize everything into relatively small, independent parts, with few relatively small, independent parts, with few interactions among theminteractions among them3Why objects?Object-oriented programming models the world as a collection of “objects”This organization:allows us to think about one object at a timeallows us to use pre-written objectsIt works best when the objects are relatively independent, rather than deeply intertwined4A fruity analogyPrograms can be like grapes—each part is complete in itself, and only loosely connected to the other partsGrapes are betterPrograms can be like pomegranates—all wrapped up together and impossible to get to one part without disturbing many other parts5Why methods?There are two main reasons for using methods:1. Objects have behaviors, and we try to have each method perform one behavior2. Methods are also a way of breaking a complex behavior down into simpler components (“Divide and conquer”)6Modeling behaviors: Example 1When you define methods, you are defining a vocabulary with which to talk about your problemclass Animal {int hunger = 10;int fatigue = 10;void eat() { hunger--; }void sleep() { fatigue = 0; }void hide() { ... }}7Modeling behaviors: Example 2class Document { String text; boolean saved; void open() { ... } void save() { ... } void edit() { ... }}8Divide and conquer: Example 1class Animal { ... void eat() { Food f = findFood(); chew(f); swallow(f); digest(f); }}9Divide and conquer: Example 2class Document { ... void open(File inFile) { String fileName = askUserForName(); if (fileExists(fileName)) { loadFile(fileName); saved = true; } else complainToUser(); }}10When do you write a method?Write a new method:If there is a particular behavior of an object that you need to implementTypically, methods like this are used from outside, to communicate something to the objectTo break a complex problem into simpler partsThe new methods should each perform a single, clearly defined taskTypically, these “sub-methods” are not made available outside the classTo do the same thing in more than one placeIt’s always a bad idea to copy code11Kinds of methodsThere are two kinds of methods:instance methods (the default kind)Can only be executed by an individual objectMay use thisMay use class variables and class methodsMay use its own instance variables and other instance methodsclass methods (denoted by the keyword static)Executed by the class itself, not by an objectMay not use this (why not?)May use class variables and class methodsMay not use instance variables or instance methods (why not?)12A common errorclass Test { int fudge = 0; public static void main(String args[]) { System.out.println(fudge); }}non-static variable fudge cannot be referenced from a static contextfudge is an instance (not static) variable—each object of type Test will have its own copy, but the class itself does notThis means the class does the work, not any particular object13When to make a method staticInstance methods are more “capable” than static methods—they can access their own instance variables and methods, as well as class variables and methodsThey are intended to be used by instances (=objects)Class (static) methods can only access class variables and methodsThey are appropriate when what you are doing does not depend on any particular objectIf a method never makes use of the instance variables or instance methods of the object, it should probably be static14Examples of static methodsYou’re tired of writing System.out.println, so you write this method: static void println(String s) { System.out.println(s);}You want to perform a task that isn’t specific to the individual object static int nextCard() { return random.nextInt(10) + 1; }15Defining a methodA method has the syntax: return-type method-name ( formal-parameters ) { method-variables code}Example: int add ( int number1, int number2 ) { int sum = number1 + number2; return sum;}16Information flowWe call a method like this: result = add( 3 , 5 ) ; int add ( int number1, int number2 ) { int sum = number1 + number2 ; return sum ;}Actual parameter values are copied into formal parametersFormal parameters are usedA result is returned17Formal parametersint add ( int number1, int number2 ) { int sum = number1 + number2; return sum;}When you enter a method, the formal parameters are created and assigned initial valuesYou must specify the types of the formal parametersThe formal parameters are variables that you can use however you likeWhen the method returns, the formal parameters are discarded18Method variablesint add ( int number1, int number2 ) { int sum = number1 + number2; return sum;}Within a method, you may create additional variablesYou can use these variables within the methodWhen the method returns, the variables are discardedFormal parameters get their values from “outside”, method variables are created “inside,” but they are otherwise alike19Primitive parameters are copied in int m
View Full Document