Java Primer II Nils Weidmann Center for Comparative and - - PowerPoint PPT Presentation

java primer ii
SMART_READER_LITE
LIVE PREVIEW

Java Primer II Nils Weidmann Center for Comparative and - - PowerPoint PPT Presentation

Introduction to Computational Modeling of Social Systems Java Primer II Nils Weidmann Center for Comparative and International Studies (CIS) Seilergraben 49, Room E.3, weidmann@icr.gess.ethz.ch Prof. Lars-Erik Cederman, CIS Room G.2,


slide-1
SLIDE 1

Introduction to Computational Modeling of Social Systems

Nils Weidmann Center for Comparative and International Studies (CIS) Seilergraben 49, Room E.3, weidmann@icr.gess.ethz.ch

  • Prof. Lars-Erik Cederman, CIS Room G.2, lcederman@ethz.ch

http://www.icr.ethz.ch/teaching/compmodels Lecture, November 16, 2004

Java Primer II

slide-2
SLIDE 2

2

Today’s agenda

  • Principles of Object-orientation
  • Classes and Instances

– RussianRoulette – CarRace

  • Inheritance

– SuvRace (extension of CarRace)

slide-3
SLIDE 3

3

Introduction to objects

User only has to be familiar with the interface of an object, not its implementation Simula-67 first

  • bject-oriented

language SmallTalk another important one Objects hide their behavior and data

slide-4
SLIDE 4

4

Object-Oriented Programming

instance variables methods An object A program

speed = 45.7; gear = 3; brake() changeGears(g)

messages An object has state, behavior, and identity (Booch)

  • bject = data + algorithms

program = objects +

slide-5
SLIDE 5

5

Three principles of OOP

  • Encapsulation

– Objects hide their functions (methods) and data (instance variables)

  • Inheritance

– Each subclass inherits all variables of its superclass

  • Polymorphism

– Same interface despite different datatypes

Car

Auto- matic Manual

Super class Subclasses draw() draw()

slide-6
SLIDE 6

6

Classes and instances

Class

Classes are "object factories". Objects are created as instances by allocating memory for them. Pointers are used to keep track of the objects.

Instances

car1 car2

Car

new Car() car3

Pointer

slide-7
SLIDE 7

7

More on Instances

Pointer Instance Car car1 = new Car(1, 65.0);

car1

Car car2 = new Car(2, 80.0);

car2

Car car3;

car3

slide-8
SLIDE 8

8

More on Instances II

Pointer Instance

car1 car2 car3

car3 = car2;

slide-9
SLIDE 9

9

More on Instances III

Instance Pointer

car1 LOST!

car1 = car2;

car2 car3

slide-10
SLIDE 10

10

Russian Roulette revisited

A B A B A 1/6 5/6 4/6 2/6 B 3/6 2/6 1/6 3/6 4/6 5/6

slide-11
SLIDE 11

11

Russian Roulette w/o objects

public class RussianRoulette { public static void main(String[] args) { int n = 1000000; //the number of replications int sum = 0; //the number of replications where player 0 dies Random rand = new Random(); //the random number generator for (int replications = 0; replications < n; replications++) { int player = 1; int i = 0; boolean shot = false; do { i++; player = Math.abs(player-1); shot = rand.nextDouble() < (double) i / 6.0; } while (!shot); if (player == 0) sum++; } double survivalProb0 = 1 - (double) sum / n; System.out.println("Player 0's probability of surviving is "+survivalProb0); } }

slide-12
SLIDE 12

12

Russian Roulette with objects

RussianRouletteWithObjects

static void main(String[] args)

Player

int numDeaths boolean shot Player() executeTry(Revolver revolver) reset()

Revolver

int numBullets void addBullet() boolean trigger()

reference!

revolver player1 player0

  • bjects

classes

slide-13
SLIDE 13

13

Russian Roulette: revolver class

public class Revolver { private int numBullets = 0; public boolean trigger() { return (Math.random() < (double) numBullets/6); } public void addBullet() { if (numBullets < 6) numBullets++; } }

instance variable methods

Static Method

slide-14
SLIDE 14

14

Russian Roulette: player class

public class Player { public int numDeaths; public boolean shot; public Player() { numDeaths = 0; } public void executeTry(Revolver revolver) { if (revolver.trigger()) { shot = true; numDeaths++; } } public void reset() { shot = false; } }

instance variables constructor methods

slide-15
SLIDE 15

15

Russian Roulette: main model

public class RussianRouletteWithObjects { public static void main(String[] args) { int numReplications = 1000000; Revolver revolver; Player player0 = new Player(); Player player1 = new Player(); for (int i=0; i<numReplications; i++) { revolver = new Revolver(); player0.reset(); player1.reset(); Player currPlayer = player1; do { revolver.addBullet(); if (currPlayer == player0) currPlayer = player1; else currPlayer = player0; currPlayer.executeTry(revolver); } while (!currPlayer.shot); } System.out.println("Player 0 died in " + player0.numDeaths + " out of " + numReplications + " replications."); } }

Constructor call creates new revolver without bullets!

slide-16
SLIDE 16

16

CarRace and SpeedTrap

cop

  • Distance per time period

drawn from uniform distribution (0,maxSpeed)

  • Total distance traveled is

the sum of all trips

  • A speed trap with

probability probCatch reduces the distance per time period to zero for any car traveling faster than the speedLimit = 65

car 1 car 2

slide-17
SLIDE 17

17

CarRace

CarRace

static void main(String[] args)

Car

int id double distance, speed, maxSpeed void drive() double getSpeed() double getDistance() void setDistance(double d)

car1 car2

  • bjects

classes

slide-18
SLIDE 18

18

Class declaration: Car

public class Car { int id; double distance, maxSpeed, speed; public Car(int i, double s) { id = i; maxSpeed = s; distance = 0.0; } public void drive () { speed = Math.random() * maxSpeed; distance = distance + speed; } public double getSpeed() { return speed; } public double getDistance() { return distance; } public void setDistance(double d) { distance = d; } }

instance variables constructor

Static Method

methods

slide-19
SLIDE 19

19

CarRace without speed trap

public class CarRace { public static void main(String[] args) { int n = 10; Car car1 = new Car(1,65.0); Car car2 = new Car(2,80.0); for (int i=0; i<n; i++) { car1.drive(); car2.drive(); System.out.println(i+" "+car1.getDistance()+" "+car2.getDistance()); } if (car1.getDistance() > car2.getDistance()) System.out.println("Car 1 won!"); else System.out.println("Car 2 won!"); } }

creating objects calling objects

slide-20
SLIDE 20

20

SpeedTrap

SpeedTrap

static void main(String[] args)

Car

int id double distance, speed, maxSpeed void drive() double getSpeed() double getDistance() void setDistance(double d)

car1 car2

classes

  • bjects

CopCar

double speedLimit, probCatch CopCar(double s, double p) intercept(Car car)

cop

slide-21
SLIDE 21

21

Adding the speed trap

public class SpeedTrap { public static void main(String[] args) { int n = 1000; Car car1 = new Car(1,65.0); Car car2 = new Car(2,80.0); CopCar cop = new CopCar(65.0, 0.7); for (int i=0; i<n; i++) { car1.drive(); car2.drive(); cop.intercept(car1); cop.intercept(car2); System.out.println(i+" "+car1.getDistance()+" "+car2.getDistance()); } System.out.print(car1.getDistance()+" "+car2.getDistance()+“ ==> "); if (car1.getDistance() > car2.getDistance()) System.out.println("Car 1 won!"); else System.out.println("Car 2 won!"); } }

new object created! new object calls!

slide-22
SLIDE 22

22

Class declaration: CopCar

public class CopCar { double speedLimit,probCatch; public CopCar(double s, double p) { speedLimit = s; probCatch = p; } public void intercept(Car car) { if (car.getSpeed() > speedLimit) if (Math.random() < probCatch) car.setDistance(car.getDistance() - car.getSpeed()); } }

slide-23
SLIDE 23

23

Inheritance

speed; gear brake() changeGears(g) speed brake() speed brake() accelerate()

Car

Car’s speed and brake() are copied to the subclasses Subclasses can add

  • wn variables and

methods

Manual Automatic

slide-24
SLIDE 24

24

SuvRace

sedan

  • Extension of CarRace
  • Distance per time

period drawn from uniform distribution (0,maxSpeed)

  • Total distance

traveled is the sum of all trips

  • The performance is

measured as the person-miles traveled

roadster

SUV SUV

slide-25
SLIDE 25

25

SuvRace

Car

Car(double s)

Sedan

Sedan(double s)

Roadster

Roadster(double s)

Suv

double probBlowOut Suv(double s,double p) void drive()

Vehicle

double distance double maxSpeed int passengers void drive() double getPersonMile()

inheritance! SUV sedan

roadster

slide-26
SLIDE 26

26

Model

public class Model { public static void main(String[] args) { int n = 100; Vehicle sedan, roadster, suv; sedan = new Sedan(65.0); roadster = new Roadster(100.0); suv = new Suv(60.0,0.01); for (int i=0; i<n; i++) { sedan.drive(); roadster.drive(); suv.drive(); } System.out.println((int)sedan.getPersonMile() + " " + (int)roadster.getPersonMile() + " " + (int)suv.getPersonMile()); } }

slide-27
SLIDE 27

27

Vehicle & Car classes

public class Vehicle { double distance = 0.0; double maxSpeed = 0.0; int passengers = 0; public void drive() { distance = distance + Math.random()*maxSpeed; } public double getPersonMile() { return distance * (double) passengers; } } public class Car extends Vehicle { public Car(double s) { distance = 0.0; maxSpeed = s; } }

slide-28
SLIDE 28

28

Suv class

public class Suv extends Vehicle { double probBlowOut; public Suv(double s, double p) { maxSpeed = s; probBlowOut = p; distance = 0.0; passengers = 7; } public void drive() { super.drive(); if (Math.random() < probBlowOut) distance = 0.0; } }

slide-29
SLIDE 29

29

Sedan and Roadster classes

public class Sedan extends Car { public Sedan(double s) { super(s); passengers = 4; } } public class Roadster extends Car { public Roadster(double s) { super(s); passengers = 2; } }

slide-30
SLIDE 30

30

ElevatorProject

1 2

  • Two tenants live in an

apartment complex with 1

  • ccupying the first floor

and 2 the second

  • The tenants move in and
  • ut of the building using

the elevator

  • Calculate the expected

waiting time for both tenants Classes Objects

Tenant Elevator

slide-31
SLIDE 31

31

Calculating expected waiting time

W(i,j) waiting time for tenant i in position j W(i,j|k) waiting time conditional on k's being last user EW(1,0) = 0.5 EW(1,0|1) + 0.5 EW(1,0|2) = 0.5 x 0 + 0.5(0.5 x 0 + 0.5 x 2) = 0.5 EW(2,0) = 0.5 x 0 + 0.5 (0.5 x 0 + 0.5 x 1) = 0.25 EW(1,1) = 0.5 x 0 + 0.5 (0.5 x 1 + 0.5 x 1) = 0.5 EW(2,2) = 0.5 x 0 + 0.5 (0.5 x 1 + 0.5 x 2) = 0.75 EW = {EW(1,0) + EW(2,0) + EW(1,1) + EW(2,2)}/4 = 0.5

slide-32
SLIDE 32

32

Elevator Project: Code

public class Model { public static void main(String[] args) { int n = 1000; Tenant tenant1 = new Tenant(1); Tenant tenant2 = new Tenant(2); Elevator elevator = new Elevator(); for (int i=0; i<n; i++) { if (Math.random()<0.5) tenant1.move(elevator); else tenant2.move(elevator); } System.out.println("Waiting time = " + elevator.averageWaitingTime()); } }

slide-33
SLIDE 33

33

Tenant class

public class Tenant { int home,floor; public Tenant(int f) { home = f; if (Math.random()< 0.5) floor = 0; else floor = f; } public boolean atHome() { return floor == home; } public void move(Elevator elevator) { elevator.callToFloor(floor); if (atHome()) elevator.takeToFloor(this,0); else elevator.takeToFloor(this,home); } }

slide-34
SLIDE 34

34

Elevator class

public class Elevator { int floor, waitingTime, numTrips; public Elevator() { if (Math.random()< 0.5) floor = 0; else floor = (int)(2.0*Math.random())+1; waitingTime = 0; numTrips = 0; } public void callToFloor(int f) { waitingTime = waitingTime + Math.abs(f-floor); numTrips++; floor = f; } public void takeToFloor(Tenant tenant,int f) { floor = f; tenant.floor = f; } public double averageWaitingTime() { return (double)waitingTime/(double)numTrips; } }