Download Ch3

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
presentation slides for
Object-Oriented Problem Solving
JAVA, JAVA, JAVA
Second Edition
Ralph Morelli
Trinity College
Hartford, CT
published by Prentice Hall
Java, Java, Java
Object Oriented Problem Solving
Chapter 3 Methods:
Communicating with Objects
Objectives
• Understand the role that methods play in an
object-oriented 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.
• Be able to use the selection control structure.
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Outline
•
•
•
•
•
•
•
•
Passing Information to an Object
Constructor Methods
Retrieving Information from an Object
Passing a Value and Passing a Reference
Flow of Control: Selection Control Structures
The Improved CyberPet
From the Java Library: Object
Object-Oriented Design: Class Inheritance
• In the Laboratory: Feeding CyberPet
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Passing Information to an Object
• Let’s add a name variable to CyberPet:
• A private variable cannot be accessed by
other objects.
• To allow other objects to access CyberPet’s
name, we will provide public accessor and
mutator methods (sometimes called “get”
and “set” methods).
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
The CyberPet.setName() Method
The str parameter serves as a
storage location for data being
passed to the method.
public class CyberPet {
...
private String name = “no name”;
...
public void setName (String str)
{
name = str;
}
...
}
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
The setName()
mutator method
assigns a String
value to CyberPet’s
name variable.
Chapter 3: Methods
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, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Parameter
Scope
Drawing boxes
around modules
helps visualize
scope.
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Arguments and Parameters
• Arguments refer to the values that are used
in the method call or method invocation.
pet1.setName("Socrates");
• 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 setName(String s) {…}
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Arguments and Parameters (cont)
Create a CyberPet instance
CyberPet pet1 = new
CyberPet();
pet1.setName("Socrates");
String s = "Hal";
pet1.setName(s);
Or,
Call setName(),
passing a String literal
pass the value (“Hal”)
stored in a String variable!
Syntax errors: setName() requires a String argument
pet1.setName(Socrates);
pet1.setName(10);
pet1.setName();
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Passing a String to CyberPet
public class TestCyberPet
{
public static void main (String argv[])
{
CyberPet pet1;
// Declare a CyberPet
pet1 = new CyberPet();
// Create a CyberPet
pet1.setName("Socrates"); // Set the pet's name
return;
// Return to the system
} // main()
} // TestCyberPet
pet1’s state after the
method call
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Parameters are Temporary Storage
(a) Before the assignment,
the parameter str refers to
“Socrates”
Java, Java, Java, 2E by R. Morelli
(b) After the assignment,
the variable name refers
to “Socrates”
Copyright 2002. All rights reserved.
Chapter 3: Methods
Parameters and the Generality Principle
• Parameters make methods more general.
• A poor design for a setName() method.
This version can only set the pet’s name to
“Socrates”:
public void setName()
{
name = "Socrates";
}
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Parameters and the Generality Principle
• We can use setName(String) to create two
CyberPets with different names:
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Constructor Methods
•
•
•
•
•
•
Used to create 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
public CyberPet(String str)
Example:
{
}
Java, Java, Java, 2E by R. Morelli
name = str;
Copyright 2002. All rights reserved.
Chapter 3: Methods
Default Constructors
• If no constructor is coded, Java provides a
default constructor.
• If a class is public, the default constructor
will also be public.
• CyberPet: Invoking the default constructor:
CyberPet socrates = new CyberPet();
Is equivalent to invoking a constructor defined as:
public CyberPet() { }
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Overloading and Method Signatures
• A method name is overloaded if there is
more than one method with the same name:
public CyberPet () { }
public CyberPet (String str)
{
name = str;
}
// Constructor #1
// Constructor #2
• 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, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
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
Constructor
definition.
invocations
CyberPet pet1 = new CyberPet();
pet1.setName("Pet1");
CyberPet pet2 = new CyberPet("Pet2");
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Retrieving Information from an Object
• Methods with non-void return types can be
used to extract 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, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
The CyberPet.getName() Method
public String getName()
{
return name;
}
pet1.setName("Socrates");
pet1.getName();
getName() takes no parameters,
and returns the value of the
name instance variable
pet1.getName() has the
value “Socrates”
System.out.println(pet1.getName());
Nested Method Call: We use
println() to print “Socrates”
We can assign “Socrates”
to a String variable
Java, Java, Java, 2E by R. Morelli
String s = pet1.getName();
Copyright 2002. All rights reserved.
Chapter 3: Methods
The Expanded CyberPet Class
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
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, CyberPet) are reference
types. Reference arguments can be changed
by a method call.
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
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, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Passing a Reference Value
• For reference parameters, a reference to an
object is passed to the method.
public void referenceCall(CyberPet p)
{
referenceCall() will be passed
p.setName("Mary");
}
a reference to a CyberPet
CyberPet x = new CyberPet("Harry");
referenceCall(x);
x refers to a CyberPet
named “Harry”
Passing x is like passing the object
itself. x’s name will be “Mary” after
the method is called.
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Passing a Reference Value
• In (a), when myMethod(pet1) is called, p
points to pet1.
• In (b), p.setName() changes pet1’s name to
“Mary”. This change will persist.
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Flow of Control: Selection 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, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
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, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Boolean Expressions
• Boolean expressions are expression that
evaluate to either true or false.
• Examples of Boolean Expressions:
true
isSleeping
false
(1 + 1) == 2
• == is the equality operator in Java
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
The getState() Method
public String getState()
{
if (isEating)
return “Eating”;
if (isSleeping)
return “Sleeping”;
return “Error in State”;
}
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
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, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
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, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Selection Statement Examples
Simple
if (isEating)
return "Eating";
If
If-then-else
if (isEating)
System.out.println("Is Eating");
else
System.out.println("Is NOT Eating");
Multiway Selection
if (isSleeping)
System.out.println("I'm sleeping");
else if (isEating)
System.out.println("I'm eating");
else if (isThinking)
System.out.println("I'm thinking");
else
System.out.println("Error: I don't know what I'm doing");
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
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");
Java, Java, Java, 2E by R. Morelli
if (condition1)
if (condition2)
System.out.println("One");
else
System.out.println("Two");
Copyright 2002. All rights reserved.
Chapter 3: Methods
The Switch/Break Structure
• Multiway selection can also be done with
the switch/break structure.
switch ( integralExpression )
{
case integralValue2 :
statement1;
break;
case integralValue2 :
statement2;
break;
…
case integrealValueN :
statementN;
break;
default:
statementDefault;
}
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Switch/Break Examples
Correct: Prints m=2
Error: Prints ch=b.ch=c, default
int m = 2;
switch (m)
{
case 1 :
System.out.println(“m=1”);
break;
case 2 :
System.out.println(“m=2”);
break;
case 3 :
System.out.println(“m=3”);
break;
default:
System.out.println(“default”);}
Java, Java, Java, 2E by R. Morelli
char ch = ‘b’;
switch (ch)
{
case ‘a’ :
System.out.println(“ch=a”);
case ‘b’ :
System.out.println(“ch=b”);
case ‘c’ :
System.out.println(“ch=c”);
default:
System.out.println(“default”);
}
Copyright 2002. All rights reserved.
Chapter 3: Methods
Inheritance: Object.toString()
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Overriding Object.toString()
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Polymorphic Object.toString()
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
In the Laboratory: Feeding CyberPet
The objectives of this lab are:
• To give practice writing Java methods from
scratch.
• To give practice using parameters to pass
information to a method.
• To give practice using return values to pass
information back from a method.
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
In the Laboratory: Feeding CyberPet
Problem Statement
Modify the CyberPet and TestCyberPet
classes to create a simulation in which pets
can eat different kinds of food. The
completed program should be capable of
producing the following output:
pet1's name is Socrates
Socrates is eating an apple
Socrates is sleeping
pet2's name is Cleopatra
Cleopatra is eating beans
Cleopatra is sleeping
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Object Design
This version of CyberPet
contains two eat()
methods.
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
Technical Terms
•
•
•
•
•
•
•
•
•
•
•
accessor method
argument
boolean expression
class scope
constructor
dangling else
dynamic binding
local scope
method definition
method invocation
method overloading
Java, Java, Java, 2E by R. Morelli
•
•
•
•
•
•
•
•
•
•
multiway selection
mutator method
parameter
primitive type
reference type
scope
selection structure
side effect
stub method
switch/break structure
Copyright 2002. All rights reserved.
Chapter 3: Methods
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, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
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, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
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, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods
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.
Java, Java, Java, 2E by R. Morelli
Copyright 2002. All rights reserved.
Chapter 3: Methods