Slide #1.

presentation slides for JAVA, JAVA, JAVA Object-Oriented Problem Solving Third Edition Ralph Morelli | Ralph Walde Trinity College Hartford, CT published by Prentice Hall
More slides like this


Slide #2.

Java, Java, Java Object Oriented Problem Solving Chapter 3 Methods: Communicating with Objects
More slides like this


Slide #3.

Objectives • Understand the role that methods play in an objectoriented program. • Know how to use parameters and arguments to pass data to an object. • Understand how constructor methods are used to instantiate objects. • Know the difference between passing a value and passing a reference to an method. • Know how to design your own methods. • Learn the if-else and while control structures. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #4.

Outline • • • • • • • • Passing Information to an Object Constructor Methods Retrieving Information from an Object Passing a Value and Passing a Reference Flow of Control: Control Structures The Improved OneRowNim From the Java Library: Object Object-Oriented Design: Inheritance and Polymorphism • Drawing Lines (Optional Graphics Methods) Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #5.

Types of Methods • A accessor method is a public method used to get the value of an object’s instance variable. – bankAccount.getAccountNumber() • A mutator method is a public method used to set the value of an instance variable. – bankAccount.setAccountNumber(1098) BankAccount -accountNumber: int +getAccountNumber(): int +setAccountNumber(int:N) Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #6.

Passing Information to an Object • Parameters are used to pass information to an object via a method. • A formal parameter is a variable that stores data while it is being passed to a method. • Parameters make methods more general. – takeSticks(int num) where num specifies how many sticks to take can replace: – takeOne(), – takeTwo(), –… Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #7.

Parameter Scope • Scope defines where a variable can be used in a program. • Local Scope: a parameter’s scope is limited to the method in which it is declared. • Class Scope: an instance variable can be accessed anywhere within the class instance. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #8.

Arguments and Parameters • Arguments refer to the values that are used in the method call or method invocation. game.takeSticks(3); • Qualified names (dot notation), are used to refer to methods within other classes. • The arguments used in the method call must match the parameters defined in method definition. public void takeSticks(int num) {…} Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #9.

Passing an int to OneRowNim • The main() method creates a OneRowNim game and invokes its takeSticks() method to remove 3 sticks: public static void main (String argv[]) { OneRowNim game; // Declare a OneRowNim object game = new OneRowNim();// Instantiate the reference game.takeSticks(3); // Remove 3 sticks } // main() public void takeSticks(int num) { nSticks = nSticks - num; player = 3 - player; } Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #10.

Parameters are Temporary Storage • Tracing the execution of game.takeSticks(3). • We use takeSticks() to change the state of the game. • The parameter num temporarily stores the value 3. Before calling takeSticks(3) After executing body of takeSticks() Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Before executing body of takeSticks() After control leaves takeSticks() Chapter 3: Methods
More slides like this


Slide #11.

Constructor Methods • Used to create and initialize an instance (object) of a class • Not inherited by subclasses • Used to initialize instance variables • Defined as public or private • Do not return a value • Example: public OneRowNim() { } nSticks = 7; player = 1; Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #12.

Constructors and Initialization • Constructors provide a flexible way to initialize an object’s instance variables • Given this constructor definition: public OneRowNim(int sticks) { nSticks = sticks; player = 1; } • We can create a 21-stick or 13-stick game: OneRowNim game1 = new OneRowNim(21); OnoRowNim game2 = new OneRowNim(13); Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #13.

Default Constructors • If no constructor is coded, Java provides a default constructor. • If a class is public, the default constructor will also be public. • OneRowNim: Invoking the default constructor: OneRowNim game = new OneRowNim(); Is equivalent to invoking a constructor defined as: public OneRowNim() { } Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #14.

Overloading and Method Signatures • A method name is overloaded if there is more than one method with the same name: public OneRowNim () { } // Constructor #1 public OneRowNim (int sticks) // Constructor #2 { nSticks = sticks; } • A method is uniquely identified by its method signature, which includes the method name plus the the number, order, and types of its parameters. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #15.

Constructor Invocation • A constructor is invoked only once, in conjunction with the new keyword, when an instance of an object is created. • The arguments in the method call must match the parameters in the method definition. Constructor invocations OneRowNim game1 = new OneRowNim(); game1.takeSticks(3); OneRowNim game2 = new OneRowNim(21); Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #16.

Retrieving Information from an Object • Methods with non-void return types can be used to retrieve information from an object. • A method that returns a value may or may not have a formal parameter list. Return Type Parameters public double average (int n1, int n2) { return (n1 + n2) / 2; } Return Value Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #17.

OneRowNim’s getSticks() Method public int getSticks() { return nSticks; } getSticks() takes no parameters, and returns the value of the nSticks instance variable OneRowNim game1 = new OneRowNim(21); System.out.println(game1.getSticks()); game1.getSticks() has the value 21 System.out.println(“Sticks= “ + pet1.getName()); We can assign the returned value to a variable Nested Method Call: We can use the returned value in method calls and expressions. int s = game1.getSticks(); Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #18.

The Expanded OneRowNim Class Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #19.

Passing a Value vs. Passing a Reference • Passing a primitive value differs from passing a reference value • Values of type int, boolean, float, and double are examples of primitive types. A primitive argument cannot be changed by a method call. • All objects (String, OneRowNim) are reference types. Reference arguments can be changed by a method call. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #20.

Passing a Primitive Value • For primitive type parameters, a copy of the argument’s value is passed to the method. public void primitiveCall(int n) { n = n + 1; } primitiveCall() will be passed an int value 5 int x = 5; primitiveCall(x); x stores the value 5 5 is copied into n when primitiveCall() is called. So primitiveCall() has no access to x itself and x remains equal to 5 even though n is incremented. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #21.

Primitive Call Example • What values will k and n have after myMethod() is invoked? public class PrimitiveCall { public static void myMethod(int n) { System.out.println("myMethod: n= " + n); n = 100; System.out.println("myMethod: n= " + n); } // myMethod() public static void main(String argv[]) { int k = 5; System.out.println("main: k= " + k); myMethod(k); System.out.println("main: k= " + k); } // main() } // PrimitiveCall Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #22.

Tracing the Passing of a Primitive Value • Tracing the values of the variables k and n. Before calling myMethod() Just after executing the body of myMethod() Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Before executing body of myMethod() After control returns to main() Chapter 3: Methods
More slides like this


Slide #23.

Passing a Reference Value • For reference parameters, a reference to an object is passed to the method. public void referenceCall(OneRowNim g) { referenceCall() will be passed g.takeSticks(3); } a reference to a OneRowNim OneRowNim x = new OneRowNim(7); referenceCall(x); Before: x refers to a OneRowNim with 7 sticks After: Passing x is like passing the object itself. x’s nSticks will be 4 after the method call. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #24.

Reference Call Example • What values will k and n have after myMethod() is invoked? public class ReferenceCall { public static void myMethod(OneRowNim g) { System.out.print("myMethod: Number of sticks: "); System.out.println(g.getSticks()); g.takeSticks(3); System.out.print("myMethod: Number of sticks: "); System.out.println(g.getSticks()); } // myMethod() public static void main(String argv[]) { OneRowNim game = new OneRowNim(10); System.out.print("main: Number of sticks: "); System.out.println(game.getSticks()); myMethod(game); System.out.print("main: Number of sticks: "); System.out.println(game.getSticks()); }// main() } // ReferenceCall Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #25.

Tracing the Passing of a Reference • Tracing the state of OneRowNim. Before calling myMethod(game) Before executing the body of myMethod() After executing the body of myMethod() After control returns to main() Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #26.

Flow of Control: Control Structures • Selection Control Structures allow the program to select one of multiple paths of execution. • The path is selected based on some conditional criteria, as is the case in a flowchart. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #27.

The Simple If Statement if ( boolean expression ) statement ; • If the boolean expression evaluates to true, the statement will be executed. Otherwise, it will be skipped. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #28.

Boolean Expressions • Boolean expressions are expressions that evaluate to either true or false. • Examples of Boolean Expressions: true nSticks <= 0 false (1 + 1) == 2 • == is the equality operator in Java Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #29.

The getPlayerString() Method public String getPlayerString() { if (player == 1) return “Player One”; if (player == 2) return “Player Two”; return “Player error”; } Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #30.

The If-Then-Else Statement if ( boolean expression ) statement1 ; else statement2 ; • If the boolean expression is true, execute statement1, otherwise execute statement2. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #31.

Multiway Selection • We can embed ifthen-else clauses to create multiway selection structures. • Note that this complicated structure has one entry and one exit. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #32.

Selection Statement Examples if (player == 1) { String s = ”Player One"; System.out.println(s); } Simple If If-then-else if (player == 1) System.out.println(”Player One"); else System.out.println(”Player Two"); Multiway Selection if (num == 1) System.out.println(”One"); else if (num == 2) System.out.println(”Two"); else if (num == 3) System.out.println(”Three"); else System.out.println("Error: unknown value"); Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #33.

The Dangling Else Problem • Rule: An else clause matches the closest previous unmatched if clause. • Indentation (which the compiler ignores) should reflect the statement’s logic. Correct Indentation Incorrect Indentation if (condition1) if (condition2) System.out.println("One"); else System.out.println("Two"); if (condition1) if (condition2) System.out.println("One"); else System.out.println("Two"); Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #34.

The While Structure • While structure to sum the squares of the numbers from 1..max: Initializers Loop body public int sumSquares(int max) { int num = 1; Loop entry condition: enter the loop int sum = 0; if this condition is true while (num <= max) { sum = sum + num * num; // Add square to sum num = num + 1; // Increment num by 1 } // while return sum; Updater: brings num closer to max }// sumSquare() • Java’s while statement: while ( loop entry condition ) loop body ; The while statement has no built-in initializer and updater. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #35.

Principles of the While Structure • Effective Design: Loop structure. A loop structure must include an initializer, a boundary condition, and an updater. The updater should guarantee that the boundary condition is reached, so the loop will eventually terminate. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #36.

Testing the Improved OneRowNim • Download, compile, and run: – OneRowNim.java and TestOneRowNim.java import java.util.Scanner; // Allows us to read keyboard input public class TestOneRowNim { public static void main(String argv[]) { Scanner sc = new Scanner(System.in); OneRowNim game = new OneRowNim(11); while(game.gameOver() == false) { game.report(); // Prompt the user System.out.print("Input 1, 2, or 3: "); // Get input int sticks = sc.nextInt(); // Get move game.takeSticks(sticks); // Do move System.out.println(); } // while game.report(); // The game is now over System.out.print("Game won by player "); System.out.println(game.getWinner()); } // main() } // TestOneRowNim Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #37.

Overriding Object’s toString() Method • To report OneRowNim’s state, we can override the toString() method inherited from Object. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #38.

Overriding toString() • We add the following method to OneRowNim: public String toString() { return “nSticks = “ + nSticks + “, player = “ + player; }// toString() • We can then use toString() as follows: public class TestToString { public static void main(String argv[]) { OneRowNim g1 = new OneRowNim(11); OneRowNim g2 = new OneRowNim(13); g1.takeSticks(2); System.out.println(g1.toString()); // nSticks = 9, player = 2 System.out.println(g2.toString()); // nSticks = 13, player = 1 } //main } //TestToString Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #39.

The Polymorphic toString() Method • A polymorphic method behaves differently when invoked on different types of objects. Object obj; obj = new Student(“12345”); // obj refers to a Student System.out.println(obj.toString()); // 12345 obj = new OneRowNim(11); // obj refers to a OneRowNim System.out.println(obj.toString()); // nSticks = 11,player = 1 Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #40.

Drawing Lines (Optional Graphics) • The Graphics class contains a drawLine() method: public void drawline(int x1, int y1, int x2, int y2) • Click on this link for a drawing demo: – Draw Sticks Demo • Download and review the source code: – DrawSticksApplet.java Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #41.

Technical Terms • • • • • • • • • accessor method class scope formal parameter if statement if-else statement local scope loop structure method overloading method signature • • • • • • • • • • multiway selection mutator method override polymorphism repetition structure scope selection side effect while statement while structure Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #42.

Summary Of Important Points • A formal parameter is a place holder in a method declaration and it always consists of a type followed by variable identifier. • An argument is a value that is passed to a method via a formal parameter when the method is invoked. • A method's parameters constrain the type of information that can be passed to a method. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #43.

Summary of Important Points (cont) • Parameter Passing. When an argument of primitive type is passed to a method, it cannot be modified within the method. • When an argument of reference type is passed to a method, the object it refers to can be modified within the method. • Except for void methods, a method invocation or method call is an expression which has a a value of a certain type. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #44.

Summary of Important Points (cont) • The signature of a method consists of its name, its return type, and the number and type of its formal parameters. • A class may not contain more than one method with the same signature. • A constructor is a method that is invoked when an instance object is created. If a class does not contain a constructor method, the Java compiler supplies a default constructor. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this


Slide #45.

Summary of Important Points (cont) • The if statement executes a statement only if its boolean condition is true. • The if-else statement statement executes one or the other of its statements depending on the value of its boolean condition. • Multiway selection allows one and only one of several choices to be selected depending on the value of its boolean condition. • The while statement is used for coding loop structures. Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 3: Methods
More slides like this