Documente Academic
Documente Profesional
Documente Cultură
objec<ves
Decomposi<on
of
a
solu<on
into
objects
and
methods
Methods
Sta<c
methods
Instance
methods
CS160
Spring
2012
Problem Decomposi<on
Read
input
Figure
out
the
loop
structure
it does!
Print output
10/8/2012
10/8/2012
Methods
Mysteries Revealed
10/8/2012
10/8/2012
Terminology
10/8/2012
10/8/2012
void says that the main func<on does not return a value
10/8/2012
import
java.u<l.Scanner;
public
class
SnowRemoval
{
public
sta<c
void
main(String[]
args)
{
System.out.println("Enter
your
address:");
Scanner
keyboard
=
new
Scanner(System.in);
String
address
=
keyboard.nextLine();
int
delay
=
snowService(address);
if(delay==0)
System.out.println("My
driveway
is
safe
now);
else
//
assume
status
is
non-nega<ve
System.out.println(I
have
to
wait
for
+
delay
+
hours);
}
10
Sta<c methods
10/8/2012
11
10/8/2012
12
public
sta<c
int
snowService(String
home){
System.out.prink("Clearing
driveway
of
%s...",
home);
System.out.println(done");
System.out.println("Clearing
sidewalk");
return
0;
}
}
10/8/2012
Communica<on
between
calling
and
called
methods
Method
parameters:
Method
declares
a
parameter
formal
parameter
(String
home)
to
state
what
can
be
provided
by
the
Caller
of
the
method
There
can
be
zero
to
any
number
of
parameters
13
10/8/2012
14
15
16
Incorrect Swapping
17
18
Decomposing processCity
10/8/2012
19
10/8/2012
20
Further simplica<on
Top-down thinking
10/8/2012
21
10/8/2012
Objects
Fancy
CS
buzzwords:
Objects
encapsulate
data
and
func3onality
Objects
encapsulate
behavior
and
state
22
Objects: Concept
An object in Java is
10/8/2012
23
10/8/2012
24
Syntax:
25
10/8/2012
26
10/8/2012
10/8/2012
28
Object Instances
For example:
Scanner aisvariable
an object
class
Declares
called
parses
that
terminal
ofcharacter
type Scanner
streams so that they can be
easily read as strings, ints
or other data types
10/8/2012
29
10/8/2012
30
Solu<on #1
10/8/2012
Initializes
be a
System
is terminal
an objecttoinstance
specific
Scanner
that reads
that
holds
information
about
from
System.in
the
system
you are on. The
data in within System
describes the input device
your terminal.
31
10/8/2012
32
Solu<on #2
10/8/2012
33
10/8/2012
Simple
example
public
class
Course
{
private
String
department,
number
private
String[]
sec<ons
=
new
String[2];
public
Course(String
dept,
String
num)
{
department
=
dept;
number
=
num;
}
public
String
getFullName(){
return
new
String(department
+
"
"
+
number);
}
public
sta<c
void
main(String[]
args)
{
Course
c1
=
new
Course("CS",
"160");
System.out.println(c1.getFullName());
}
10/8/2012
CS 160, Fall Semester 2012
}
34
35
10/8/2012
36