GWU

CS 1111

Introduction to Software Development

GWU Computer Science


Lecture Notes 19: Classes and Object-Oriented Design


Objectives

By the end of this module, you will be able to:




Before Starting

If you do not have your Codio course ready, use any text editor or simple IDE. Some possibilities are:




A Visualization of the FBUser example:

FBUser Visuailzation




Object-Oriented Programming (OOP): Goodbye Static!

We can now better understand the static keyword.



An Example with static and non-static variables and methods:

public class StaticExample {
  private static int staticVar;
  private int objectVar;

  public static void staticSetVar(int val) {
    staticVar = val;    
  }
  public static int staticGetVar() {
    return staticVar; 
  }
  
  public void objSetVar(int val) {
    objectVar = val;
  }
  public int objGetVar() {
    return objectVar; 
  }
}

public class TestStaticExample {
  public static void main(String[] args) {
    StaticExample.staticSetVar();
    System.out.println ( StaticExample.staticGetVar() );

    StaticExample ob1 = new StaticExample();
    ob1.objSetVar();
    System.out.println ( ob1.objGetVar() );
  }
}

Visualizing this:



Activity 1 [Group Work] (2-minutes): Compile and Run the following example. What errors do you get? Fix them where possible.

public class StaticExample2 {
    private static int staticVar;
    private int objectVar;

    public void objSetVars() {
        objectVar = 10;
        staticSetVars();
    }
    public int[] objGetVars() {
        return new int[]{staticvar, objectVar}; 
    }
    public static void staticSetVars() {
        staticVar = 10;    
        objSetVars();
    }
    public static int[] staticGetVars() {
        return new int[]{staticvar, objectVar}; 
    }
    public static void main(String[] args) {
        staticSetVars();
        objSetVars();

        StaticExample v = new StaticExample();
        v.staticSetVars();
        v.objSetVars();
    }
}




Null Objects

null is a valid value for a variable of any non-primitive type. This includes:

null is simply a reference to nothing



public class NullTest {
    private int n;
    public int getN() {
        return n;
    }
    public static void main(String[] args) {
        NullTest nt = null;
        System.out.println(nt.getN());
    }
}

Activity 2 (2-minutes): Execute this program. What happens when this program is executed? Why?

Activity 3 (2-minutes): What is the default value for variables of a class's type? Write a small program TestDefault.java to print out the default value of the variable:

FBUser u;




Constructors

If a class gives the blueprint to create objects, constructors lay the initial foundation for each object.

Constructors are methods that are invoked when a new object is created that are used to initialize the data of the new object.

FBUser u = new FBUser();

new FBUser(); invokes the constructor on the newly created object.

The constructor can be overloaded just like any other method:

FBUser u = new FBUser("chester", "thecat");

What does a constructor look like? An example:

public class FBUser {
    private long userId;
    private String firstName, lastName;
    private FBUser[] friends;

    public FBUser() {
        // initialize object's data here
    }
    public FBUser(String first, String last) {
        firstName = first;
        lastName = last;
    }
    public void setId(long id) {
        userId = id;
    }
    public long getId() {
        return userId;
    }
}

Activity 4 [Group work] (3-minutes): Add a print statement to the constructor to see when it is invoked.

Initialize the data in the constructor (Id, firstName, lastName). Then add ccode to FBUserTest.java that uses the getters in order to verify it was initialized correctly.




Classy Scope

Where is the problem in the following code?

public class FBUser {
    private long userId;
    private String firstName, lastName;
    private FBUser[] friends;

    public FBUser(String firstName, String lastName) {
        // uh oh...
    }
    public void setId(long id) {
        userId = id;
    }
    public long getId() {
        return userId;
    }
}

Scope works the same with an object's variable as it did for global variables:

public class FBUser {
    private long userId;
    private String firstName, lastName;
    private FBUser[] friends;

    public FBUser(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    public void setId(long id) {
        userId = id;
    }
    public long getId() {
        return userId;
    }
}

this is, generically, a variable that references the "current" object.

If a method takes a FBUser argument, or a variable holds a FBUser, this can be used.

public class FBUser {
    private long userId;
    private String firstName, lastName;
    private FBUser[] friends;

    public FBUser() {
        friends    = new FBUser[10];
        friends[0] = this;
    }
}

Note the usefulness of the cocnstructor to initialize reference types inside the object! This gets done only once at the creation of the object.

Activity 5 [Group work] (3-minutes): Add a method to your FBUser class:

void addFriend(FBUser friend)

However, add a check that will prevent a FBUser from adding itself to its own friend list. In the main, this undesirable action might be done with:

  FBUser user = new FBUser();
  user.addFriend(user);

Activity 6 [Group work] (3-minutes): Add a method to your FBUser class:

void addAsFriend(FBUser otherUser)

This method adds the current FBUser as a friend in the otherUser.




Zombies. Objectified Zombies. Yeeeees.

Zombies...

Humans...

Activity 7 (Asynchronous):
  1. Make a Person class, and a ZombiesMain class. The latter has the main that will use the Person class.
  2. Each Person object is either a human or a zombie.
  3. If a Person object is a human, it has a name.
  4. Humans can shoot Person objects.
  5. Zombies can bite humans, which turns them into a zombie.
  6. Person objects created with constructors with no arguments are zombies.
Your job is to define a set of methods and data for the Person class that will tell a story when each of the humans and zombies take actions. All of your data in the Person class must be private. Be creative!!! A possible story line follows:

Person joe  = new Person("Joe");
Person bob  = new Person("Bob");
Person jane = new Person("Jane");
Person z    = new Person();

System.out.println(Person.numHumans() + " humans vs. " + Person.numZombies() + " zombies.");
z.bite(bob); // poor bob
bob.bite(z); // confused zombie
Person derpbie = bob;
derpbie.bite(derpbie); // this is getting ridiculous
System.out.println(Person.numHumans() + " humans vs. " + Person.numZombies() + " zombies.");

jane.shoot(z);    // humans FTW!
jane.shoot(joe);  // wait...what?
jane.shoot(jane); // oh...oh no.
System.out.println(Person.numHumans() + " humans vs. " + Person.numZombies() + " zombies.");

while (true) {
    derpbie.bite(derpbie); // bored zombie is bored
}

An example execution of this program would be:
Joe, ready for action!
Bob, ready for action!
Jane, ready for action!
...mmmm, brains.  Oh noes, a zombie!
3 humans vs. 1 zombies.
Bob is gnawed on by a zombie.
The zombie formerly known as Bob bites a zombie, like an idiot.
The zombie formerly known as Bob is hungry...and remembers he has an arm.  Nomnomnomnom.
...etc...




OO Design

Why does Object-Oriented Programming (OOP) exist?

Activity 8 (Asynchronous): Imagine you wanted to write a card game platform to support playing many different card games.

Design a set of classes and objects to describe cards for the card game "War". Write "prototype" classes that include the classes, data in the classes, and methods, but do not provide an implementation of the methods.

A fundamental goal of object oriented design is reuse. Activity 9 (Asynchronous):

Take your design from the previous Exercise.

Redesign your objects so that many of them can be reused between games

Other factors to consider: