Class 6: Transition to Objects: Grouping Data with Functions


Member functions and constructors
We talked about member functions and constructors. See Dr. Crabbe's notes and your notes.

Example
As an example we looked at how we might've started to define a class for a player from the previous lab using constructors and member functions:

Player.javaGame.java
public class Player
{
  //-- DATA ---------------------------------------//
  // Represent direction: N = 0, E = 1, S = 2, W = 3
  public int row, col, dir;
  public char sym;

  //-- CONSTRUCTORS ------------------------------//
  private Player() { row = col = dir = 0; sym = '?'; }

  public Player(int r, int c, int d, char s)
  {
    row = r; col = c; dir = d; sym = s;
  }
  public Player(char d) 
  { row = col = 0;
    dir = d == 'N' ? 0 : (d == 'E' ? 1 : (d == 'S' ? 2: 3)); 
    sym = '?'; 
  }

  //-- OTHER MEMBER FUNCTIONS --------------------//
  public void turnRight() 
  {
    dir = (dir + 1) % 4; 
  }
  public String toString()
  {
    return sym + ":(" + row + "," + col + "):" + dir;
  }
}
public class Game
{
  public static void main(String[] args)
  {
    Player p1 = new Player(20,0,1,'@');
    System.out.println(p1);
    p1.turnRight();
    System.out.println(p1);
  }
}


Christopher W Brown
Last modified: Wed Aug 19 11:00:04 EDT 2009