Sunteți pe pagina 1din 9

Learning

objec<ves
Decomposi<on of a solu<on into objects and
methods
Methods

Classes, Objects, and Methods

Sta<c methods
Instance methods

CS160
Spring 2012

Sharing data between methods


Local Data
Class Data
10/8/2012

Problem Decomposi<on

But shouldnt the language help us decompose


problems?

Read input
Figure out the loop structure

it does!

Decompose a big method into smaller methods

Ini<alize variables (loop counters, accumula<ng


variables, such as totals)
Find an appropriate loop termina<ng condi<on
Figure out what happens inside a loop

We will see two ways of doing this (sta<c and


instance methods)

Decompose into objects (and classes)

Perhaps nested loops

We introduce this topic with a simple example, but


more details are covered in CS161, CS200, CS314, ...

Print output

CS 160, Fall Semester 2012

Problem Decomposi<on (contd)

As discussed in previous slides:

10/8/2012

CS 160, Fall Semester 2012

10/8/2012

CS 160, Fall Semester 2012

Methods

Mysteries Revealed

A method (a.k.a. func<on, procedure, rou<ne)


is a piece of code that performs a useful ac<on

public class Temperature {


public static void main(String[] args) {
// your code here
}
}

You dened a rou<ne called main.


When you run a Java program, it always begins by
running the main method.

Methods can also return a value to the program


that called them
More details in a minute

10/8/2012

CS 160, Fall Semester 2012

In the last assignment


(P7), you defined a
class called
Temperature!
5

10/8/2012

Terminology

They are of two types

Combines variables with methods

A class is like a set (denes the proper<es of


the elements)
An object is an instance of a class
Objects are elements of the set (an object has
the proper<es dened in the class)

CS 160, Fall Semester 2012

CS 160, Fall Semester 2012

Data inside objects and classes

A class is a data type

10/8/2012

You also defined a method


(think function) called main
that took an array of Strings as
its arguments

They may belong to the class (and will take the


same value for all the objects)
They may belong to the object (and can take
dierent values for each object)

10/8/2012

CS 160, Fall Semester 2012

Another mystery: sta<c

public sta<c void main

In order to call a method, you need an


instance of the class

Remember that magic incanta<on at the start


of your program?

You must have a String variable called word to call word.length()


The length() method can access data in the instance it is called on
Such methods are called instance methods

main is the name of your method


main is the method called by the OS

void says that the main func<on does not return a value

Excep<on: sta<c methods

What would the OS do with a return value?

sta<c promises that main will not access instance


variables

Not all methods need to access data specic to objects


Sta<c declares that a method will not access instance data
Sta<c methods can be called without a class instance
Uses the nota<on classname.method()
Sta<c methods may access class data, but not instance data
10/8/2012

CS 160, Fall Semester 2012

Because the OS needs to call it without crea<ng a class instance

public is des<ned to remain a mystery just a bit longer.

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);
}

main is an example of a sta<c method


It can only access class variables (or sta<c
variables)
Therefore main cannot access instance
variables. To use instance variables, we will
have main create an instance of its class
But rst, lets see some sta<c methods
First we will see sta<c methods that dont share data
Then we will see sta<c methods that can share data
CS 160, Fall Semester 2012

10

Simple example (main method


calling snowService)

Sta<c methods

10/8/2012

CS 160, Fall Semester 2012

11

10/8/2012

CS 160, Fall Semester 2012

12

Simple example (snowService


method)

Using arguments and return values


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

CS 160, Fall Semester 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

Method return type and value:


Can return void (i.e., nothing) or a type (e.g., int, char, int[], String, etc)
If a type is returned, there must be a return statement in the method
body

Calling method (in this case main):

13

10/8/2012

Communica<on using sta<c


variables
public class Fun {
sta<c int data = 0;
public sta<c void main (String[] args) {
System.out.println(Storing 5 into store);
store(5);
System.out.println(Retrieving + retrieve() + from store);
}
public sta<c void store(int value) {
data = value;
}
public sta<c int retrieve() {
return data;
}
}

10/8/2012

CS 160, Fall Semester 2012

Supplies arguments (actual parameters) that must match the type of


the parameters in the method declara<on
Uses the return value to do something
CS 160, Fall Semester 2012

14

Cau<on: Pass by value


What do you expect this to print?
public class PassByValue {
public sta<c void main(String[] args) {
int num = 100;
increment(num);
System.out.println("Aoer calling increment, num is " + num);
}
public sta<c void increment(int n) {
n++;
}
}

15

The value of the argument is copied. Any changes to the copy


are not reected in the original argument.
10/8/2012

CS 160, Fall Semester 2012

16

Incorrect Swapping

Cau<on: Pass by value


Another example
public class PassByValueString {
public sta<c void main(String[] args) {
String word = new String("Good morning");
changeGree<ng(word);
System.out.println("Aoer calling changeGree<ng, word is " + word);
}

public sta<c void changeGree<ng(String w) {
w = new String("Good night");
}
}

Gree<ng remains unchanged


10/8/2012

CS 160, Fall Semester 2012

17

public class Swapper {


public sta<c void main(String[] args) {
String s1 = "Mar<n";
String s2 = "Scorcese";
swap(s1, s2);
System.out.println(main: Aoer swap, s1=" +s1+ " and s2=" +s2);
}

public sta<c void swap(String x, String y) {


System.out.println(swap: Before swap, x= +x+ and y= +y);
String temp = x; x = y; y = temp;
System.out.println(swap: Aoer swap, x=" +x+ " and y=" +y);
}
}

Nothing gets swapped!


10/8/2012

Simplifying Temperatures main


method

Refer to sample program version 2 (called


Temperature2.java)
In version 1, processCity was doing three
logical tasks:
Ini<alizing the counters
Reading the le to set the counters
Prin<ng the histogram

Check the number of command-line args


Print error message and exit if there are no arguments
Otherwise, loop through each argument and

Version 2 makes two new methods, one for


reading the le and the other for prin<ng the
histogram

call processCity on each argument


CS 160, Fall Semester 2012

18

Decomposing processCity

Original code with one long main method


(Temperature0.java)
Refer to sample program version 1 (called
Temperature1.java)

Pseudo-code

10/8/2012

CS 160, Fall Semester 2012

19

10/8/2012

CS 160, Fall Semester 2012

20

Further simplica<on

Use methods for subtasks

For prin<ng the histogram, prin<ng stars can be


taken out as a separate method (see
Temperature3.java)
There can be many dierent ways of decomposing a
solu<on

The general rule is:


Break subtasks into tasks un<l tasks are trivial
Every subtask is a method
Some methods (subtasks) may call others

Reuse can be taken into account


Ooen, smaller methods can be reused in other programs

Top-down thinking

Break up a big program into smaller pieces


The main method calls the other pieces. The
pieces can themselves call other pieces

10/8/2012

CS 160, Fall Semester 2012

21

10/8/2012

Objects

The idea is that a program manipulates data


via methods (func<ons)

A set of methods (think: func<ons)


A set of members (think: variables)

In P7, the temperature les were an important


collec<on of data
So, too, was the names of the text les submised
by the user on the command line
You wrote a method (called main)

Fancy CS buzzwords:
Objects encapsulate data and func3onality
Objects encapsulate behavior and state

CS 160, Fall Semester 2012

22

Objects: Concept

An object in Java is

10/8/2012

CS 160, Fall Semester 2012

23

10/8/2012

CS 160, Fall Semester 2012

24

Object Example: String

Another example: Scanner


Scanner is a more complex object
Its data is a stream of characters

You have been using objects all along


String is an example of an object in Java

May come from a le


May come from the terminal (a stream)
May come from a string

The characters are the data in the object


Methods include:

Its ac<ons are to parse and interpret the


characters

length() : how long is the string?


charAt(int): what character is at a given posi<on?

Syntax:

next() returns the next valid string


nextInt() returns the next valid integer
nextDouble() returns the next valid double
and there are many more (see on-line Java
reference)

You call an objects method using . and args ()


E.g.: word.charAt(5); word.length()

You access an objects data using just .


10/8/2012

CS 160, Fall Semester 2012

25

10/8/2012

Yet another example: arrays

Classes are data types (just like primi<ves):


int counter;
String word;
MyClass example;

Their data is a set of variables of the type


provided
Their data includes a variable that stores the
length of the array

By conven<on, class names are capitalized


Variables with object types s<ll need names

Note that array lengths are stored in variables, not


computed by func<ons
This is why there are no ()s aoer args, if args is an
array.
CS 160, Fall Semester 2012

26

Classes as data types

Arrays are the simplest objects

10/8/2012

CS 160, Fall Semester 2012

E.g. counter, word, and example above

Variables cannot be used un<l they are assigned


values
True for both primi<ve and object types
27

10/8/2012

CS 160, Fall Semester 2012

28

Object Instances

More Mysteries Revealed

The value assigned to a variable of an


object type is an object instance

Scanner terminal = new Scanner(System.in);

Just like 9 is an instance of int (except that


int is not a class, its a primi<ve type)

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

String word = new String(the);


word is a variable of type String.
String(the) creates an instance of String

All 0bject instances are created using the


keyword new.

10/8/2012

CS 160, Fall Semester 2012

29

10/8/2012

Methods inside a class


Generally constructors are wrisen rst

Shared data problem: what if two methods need to


share data?

30

Method1 for subtask 1 returns a value,v


Method2 for subtask 2 uses the value,v
Example:
public sta+c void main(String[] args) {
String[] wordList = readInput();
processWords(wordList);
}

One subtask reads input and creates an array of words


Another subtask checks each word in the array and does
something with it

CS 160, Fall Semester 2012

CS 160, Fall Semester 2012

Solu<on #1

Order of wri<ng methods is arbitrary

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

CS 160, Fall Semester 2012

32

Solu<on #2

Data Variables in Classes

Use instance variables

How does a method access data in a class?

Dene String[] wordList; as an instance variable


Any method of a class can access its variables

Every method can access the class instance it is called on


Think of word.length(); it can access the data in the string word
Think of the class instance as a hidden argument to the method

readInput() can create & write the array


processWords() can access it

Class variables look like any other variables in the code of


a method
They do not need to be re-declared

10/8/2012

CS 160, Fall Semester 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
}

CS 160, Fall Semester 2012

34

Temperature example using


instance methods
Refer to the example posted under sample programs.
This is version 4 (called Temperature4.java).
Shows one way to dene a constructor and instance methods
that operate on the objects data.

35

10/8/2012

CS 160, Fall Semester 2012

36

S-ar putea să vă placă și