teaching machines

CS 145 Lecture 35 – A World of Objects

November 24, 2014 by . Filed under cs145, fall 2014, lectures.

Agenda

TODO

Think About This

Games are often modeled by representing each of a game’s “nouns” as an object. The objects interact with one another.

You are writing a social farming game. Identify on your own an object in your game. What are its behaviors (methods), that other objects can trigger? What is its state (instance variables)?

With a partner, discuss your objects. Find a way for your objects to interact, invoking each other’s behaviors.

Code

UhOh.java

package lecture1124;

public class UhOh {
  public static void main(String[] args) {
    adInfinitum();
  }
  
  public static void adInfinitum() {
    adInfinitum();
  }
}

Finally.java

package lecture1124;

import java.io.IOException;
import java.io.PrintWriter;

public class Finally {
  public static void main(String[] args) {
    PrintWriter out = null;
    try {
      out = new PrintWriter("/Users/johnch/Desktop/foo.txt");
      out.println("asdfadsfads");
      String stringWithNumber = "dog51";
      int i = Integer.parseInt(stringWithNumber);
    } catch (IOException e) {
    } finally {
      if (out != null) {
        out.close();
      }
    }
  }
}

StopWatch.java

package lecture1124;

public class StopWatch {
  private long startTime;
  private long stopTime;

  public void start() {
    startTime = System.currentTimeMillis();
  }
  
  public void stop() {
    stopTime = System.currentTimeMillis();
  }
  
  public void reset() {
  }
  
  public double getElapsedSeconds() {
    return (stopTime - startTime) / 1000.0;
  }
}

Alphabet.java

package lecture1124;

import java.util.Scanner;

public class Alphabet {
  public static void main(String[] args) {
    StopWatch timer = new StopWatch();
    timer.start();
    
    // do some long running activity
    Scanner in = new Scanner(System.in);
    System.out.print("Enter alphabet backwards: ");
    String line = in.nextLine();
    System.out.println(line.equals("zyxwvutsrqponmlkjihgfedcba"));
    
    timer.stop();
    System.out.println(timer.getElapsedSeconds());
  }
}

Haiku

on state and behavior:
Dad can’t fix my car
Or read to his grandchildren
With 0 HP