Lecture 14: Introduction to Classes and Objects

nutmegactSoftware and s/w Development

Nov 11, 2012 (4 years and 9 months ago)

220 views

Lecture 16:


CS201

Definition: State

2


State is the configuration of data at one point in
time


An object’s state is the set of values of its data
fields at one instant

Test Your Work Incrementally

3


We are writing a program in which a store tracks a group of
salespeople. We need to be able to list the salespeople by name
and year
-
to
-
date sales


The store is modeled by an object of class Store


The staff is modeled by an array of objects of class Salesperson



Store must have a name, an array of Salesperson objects, ways
to get data for these fields, a toString(), and a method to list all
the salespeople, using data from the objects.


Salesperson must have a lastname, a firstname, an id number, a
double for year to date sales, some getters and setters, and a
toString() method. It should probably have a constructor that
takes the names as parameters.



Test Your Work Incrementally

4


Two approaches:


Top
-
Down: write the high level class (Store) first


Store has “dependencies”: it needs Salesperson to work correctly. If we write it first, we must “stub
out” some of the methods or write simulations, then fill in the details later.


This approach is analytical; it takes things apart




Bottom
-
Up: write the low
-
level class (Salesperson) first, then write Store.


Salesperson doesn’t depend on anything else, so we can write everything we know it needs all at
once, although we will inevitably later realize we need to add more.


This approach is synthetic; it puts things together



Both have strengths and weaknesses


Bottom
-
up is simpler, but top
-
down matches the way we typically think out the project
initially.



Either way, try to write the smallest unit of code that you can test. Get it
working before you proceed any farther. Repeat until you are done!



Top
-
Down: Write Store First

5

package store;


public class Store {

private String name;

private Salesperson[] staff; // we must stub out the Salesperson class for this to work, but it doesn’t need anything bey
ond

a class signature and one set of curly braces.



public static void main(String[] args){

Store myStore =
new Store();

myStore.testStore();

}


private void testStore(){

Store thisStore =
new Store();

thisStore.setName("Viking Furniture");

thisStore.setStaffFromInput();

System.
out.println(thisStore.toString());

System.
out.println(listStaff());

}


public void setName(String nameIn){


name = nameIn;

}


public void setStaffFromInput(){

// This method will take input to create the salespeople. We can't make this work until Salesperson is working, so we just w
rit
e a stub

}


public String toString(){


return name;

}


public String listStaff(){

// can't make this work until after we get Salesperson working


return "listStaff not implemented yet";

}

}

Test Your Work Incrementally

6

Let’t test it:

Output:


Viking Furniture

listStaff not implemented yet




So far, Store is working as intended. Next, we implement Salesperson, the update the
methods in Store to use actual Salesperson data.




Bottom
-
Up: Write Salesperson First

7

package store;


public class Salesperson {


private String lastName;


private String firstName;


private int id;


private double ytdSales;



public Salesperson(String lastIn, String firstIn){



lastName = lastIn;



FirstName = firstIn;


}



public String toString() {



return lastName + ", " + firstName + ": id# " + id + "YTD Sales: "



+ ytdSales;


}



public String getLastname() {



return lastName;


}



public void setLastname(String lastName) {



this.lastName = lastName;


}



public String getFirstName() {



return firstName;


}



public void setFirstName(String firstName) {



this.firstName = firstName;


}



public int getId() {



return id;


}



public void setId(int id) {



this.id = id;


}



public double getYtdSales() {



return ytdSales;


}



public void setYtdSales(double ytdSales) {



this.ytdSales = ytdSales;


}


}


Bottom
-
Up: Write Salesperson First

8



Now write a version of Store that just tests Salesperson:

package store;


public class Store {


private String
name;


private Salesperson[]
staff;



public static void main(String[] args){



testSalesperson();


}



private static void testSalesperson(){



String testFirstName = "Abel";



String testLastName = "Baker";



double testYTDSales = 1000.0;


Salesperson p =
new Salesperson(testLastName, testFirstName);


int testId = 1;


p.setId(testId);


p.setYtdSales(testYTDSales);


if(!(p.getLastName().equals(testLastName))) System.
out.println("first name error");


if(!(p.getFirstName().equals(testFirstName))) System.
out.println("first name error");


if(p.getId() != testId) System.
out.println("ID error");


if(p.getYtdSales() != testYTDSales) System.
out.println("Sales error");


System.
out.println(p.toString());


}

}

Bottom
-
Up: Write Salesperson First

9





Once Salesperson is working correctly, then proceed to write the
rest of Store

King of Hearts’ Algorithm

10

" '
Where shall I begin, please your
majesty?' he asked.

'Begin at the beginning,' the King said
gravely, 'and go on till you come to the
end; then stop.'

"

Recursive Algorithm

11

The Reverse King of Hearts’ method:


Function
DoSomething

1.
If you are finished, stop

2.
Else

1.
Solve part of the problem

2.
Run this algorithm


Recursion

12


For example, we can define the
operation
goHome
() as:


If you are at home, stop moving.


Otherwise


Take one step toward home.


goHome
()



Factorial: non
-
recursive

13

function

factorial is:

input
: integer
n

such that
n

>= 0

output
: [
n

×

(
n
-
1)
×

(
n
-
2)
×


×

1]

Iterative algorithm


1.
create new variable called
running_total

with a value of 1

2.
begin loop

1.
if
n

is 0, exit loop

2.
set
running_total

to (
running_total

×

n
)

3.
decrement
n


4.
repeat loop

3.
return
running_total


end factorial

Recursion

14

You will see this algorithm again in future classes!


function

factorial:

input
: integer
n

such that
n

>= 0

output
: [
n

×

(
n
-
1)
×

(
n
-
2)
×


×

1]


1.
if
n

is 0,
return

1
//
what do you think of that, Zeno?

2.
otherwise,
return

[
n

×

factorial(
n
-
1) ]


Recursion

15

public class JerseyShoreRecursive{


private static String johnName = "John";


private static String colinName = "Colin";




public static void main(String[] args){



int distanceToShore = Integer.parseInt(args[0]);



goShore(distanceToShore);



}



public static void goShore(int distance){



if(distance == 0) {




System.out.println("
\
nWe're there!");




return;



}



else{




String name = null;




if(distance % 2 == 0) name = johnName;




else name = colinName;




System.out.println("
\
nAre we there yet?");





System.out.println("No, " + name + ", we still have " + distance +
" miles to go. And stop hitting your cousin!");




}



goShore(distance
-
1);


}

}

Recursion

16

Function
recurse
()


1.
If you are done with your program, stop

2.
Otherwise, work on your program

3.
Note that it does not work

4.
Utter an obscenity

5.
r
ecurse
()



Inheritance

17


Classes often have natural hierarchies, which
can be defined in terms of data or in terms of
functionality


The simplest form of hierarchy is general
-
to
-
specific


Inheritance

18


All vehicles have some variables in common


weight


source of locomotion


manufacturer


Motor vehicles are a subset of vehicles, and
they have additional data fields


Engine type


Number of
wheels


Trucks are a subset of motor vehicles, and
they have yet more data fields


Hauling capacity


Etc





Inheritance

19


We can model this kind of general
-
to
-
specific
hierarchy using
class inheritance



One class can be a subclass of another



This hierarchy can be as deep as we like



To define a class as a subclass of a superclass, use
the
extends

keyword. See the examples below



Inheritance

20


Subclasses inherit methods and variable definitions
from superclasses, and can also add their own



Subclasses can also
override
inherited

methods


This is what happens when we define a toString() method;
it overrides the one inherited from Object



It is much easier to use an IDE like Eclipse for apps
that use inheritance than to try to do this with the
command line.


Review and Exam Prep

21


Questions?

22


Evaluations