DOC PREVIEW
Penn CIT 591 - Methods

This preview shows page 1-2-3-27-28-29 out of 29 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

MethodsComplexityWhy objects?Why 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 22Using instance methods IUsing instance methods IIUsing instance methods IIIUsing class methods IUsing class methods IIVocabularyThe EndMethodsComplexity•The programmer's biggest adversary is The programmer's biggest adversary is complexitycomplexity•Primitive 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 computation•Everything 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 complexity•In 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 themWhy objects?•Object-oriented programming models the world as a collection of “objects”•This organization:–allows us to think about one object at a time–allows us to use pre-written objects•It works best when the objects are relatively independent, rather than deeply intertwinedWhy 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”)Modeling behaviors: Example 1class Animal {int hunger = 10;int fatigue = 10;void eat() { hunger--; }void sleep() { fatigue = 0; }void hide() { ... }}Modeling behaviors: Example 2class Document { String text; boolean saved; void open() { ... } void save() { ... } void edit() { ... }}Divide and conquer: Example 1class Animal { ... void eat() { Food f = findFood(); chew(f); swallow(f); digest(f); }}Divide and conquer: Example 2class Document { ... void open(File inFile) { String fileName = askUserForName(); if (fileExists(fileName)) { loadFile(fileName); saved = true; } else complainToUser(); }}When do you write a method?•Write a new method:–If there is a particular behavior of an object that you need to implement•Typically, methods like this are used from outside, to communicate something to the object–To break a complex problem into simpler parts•The new methods should each perform a single, clearly defined task•Typically, these “sub-methods” are not made available outside the classKinds of methods•There are two kinds of methods:–instance methods (the default kind)•Can only be executed by an individual object•May use this•May use class variables and class methods•May use its own instance variables and other instance methods–class methods (denoted by the keyword static)•Executed by the class itself, not by an object•May not use this (why not?)•May use class variables and class methods•May not use instance variables or instance methods (why not?)A common error•class 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 objectWhen to make a method static•Instance methods are more “capable” than static methods—they can access their own instance variables and methods, as well as class variables and methods–They are intended to be used by instances•Class (static) methods can only access class variables and methods–They are appropriate when what you are doing does not depend on any particular objectExamples of static methods•You’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 int nextCard() { return random.nextInt(10) + 1; }—I didn’t make this static, but I should have!Defining a method•A 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;}Information flow•We 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 returnedFormal parameters•int add ( int number1, int number2 ) { int sum = number1 + number2; return sum;}•When you enter a method, the formal parameters are created and assigned initial values•You must specify the types of the formal parameters•The formal parameters are variables that you can use however you like•When the method returns, the formal parameters are discardedMethod variables•int add ( int number1, int number2 ) { int sum = number1 + number2; return sum;}•Within a method, you may create additional variables•You can use these variables within the method•When the method returns, the variables are discarded•Formal parameters get their values from “outside”, method variables are created “inside,” but they are otherwise alikePrimitive parameters are copied in int m = 3;int n = 5;result = add( m , n ) ; int add ( int number1 , int number2 ) { while (number1 > 0) { number1--; number2++; } return number2 ;}The values of m and n (that is, 3 and 5) are copied to the formal parametersChanging number1 and number2 does not affect m and n• This is call by valueThe value of number2 is returned, but the variable number2 is thrown awayObjects are different Person p = new Person("John");Person p actually allocates space to hold a reference to a Personp:new Person("John") allocates space for the actual Person, and initializes it"John"The


View Full Document

Penn CIT 591 - Methods

Documents in this Course
Stacks

Stacks

11 pages

Arrays

Arrays

30 pages

Arrays

Arrays

29 pages

Applets

Applets

24 pages

Style

Style

33 pages

JUnit

JUnit

23 pages

Java

Java

32 pages

Access

Access

18 pages

Arrays

Arrays

32 pages

Methods

Methods

9 pages

Methods

Methods

29 pages

Vectors

Vectors

14 pages

Eclipse

Eclipse

23 pages

Vectors

Vectors

14 pages

Recursion

Recursion

24 pages

Animation

Animation

18 pages

Animation

Animation

18 pages

Static

Static

12 pages

Eclipse

Eclipse

23 pages

JAVA

JAVA

24 pages

Arrays

Arrays

29 pages

Animation

Animation

18 pages

Numbers

Numbers

21 pages

JUnit

JUnit

23 pages

Access

Access

18 pages

Applets

Applets

24 pages

Methods

Methods

30 pages

Buttons

Buttons

20 pages

Java

Java

31 pages

Style

Style

28 pages

Style

Style

28 pages

Load more
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?