Object-Oriented Programming

Douglas Blank, Bryn Mawr College, CS206, Spring 2016

Topics:

  • classes
  • instances
  • methods
  • fields/properties

Objects

An object is a new type of thing, like String, int, or float.

You define a new type of object using the class keyword.

You create an instance of an object using the new keyword.

The simplest kind of class:

In [ ]:
class Dog {

}
In [ ]:
Dog dog1 = new Dog();

A bit more complicated:

In [ ]:
class Dog {
    String name;
    
    Dog(String name) { // constructor
        this.name = name;
    }
    
    void speak() {
        printf("woof, woof! My name is %s", this.name);
    }
}

Making an instance:

In [ ]:
Dog dog1 = new Dog("Snoppy");

Making a bunch of instances:

In [ ]:
Dog dog2 = new Dog("Gracie");
Dog dog3 = new Dog("Louis");
Dog dog4 = new Dog("Mr. Puddles");
Dog dog5 = new Dog("Kirena");
Dog dog6 = new Dog("Pepper");
Dog dog7 = new Dog("Woofie");
Dog dog8 = new Dog("Boo");
In [ ]:
dog1.speak();
dog2.speak();
dog3.speak();
dog4.speak();
dog5.speak();
dog6.speak();
dog7.speak();
dog8.speak();

Another new type:

In [ ]:
class Student {
    String name;

    Student(String name) {
        this.name = name;
    }
}
In [ ]:
Student student1 = new Student("Kevin");
In [ ]:
Student student2 = new Student("Taylor");

Expressions

In [ ]:
student1.name == student2.name

Data Structures

Imagine a chain link:

We will use this idea to create a "linked list"

Linked List

  • starts out with no items (we'll call them nodes)
  • we add new links/nodes onto the end
In [ ]:
class Node {
    String name;
    Node next;
    
    Node(String name) {
        this.name = name;
    }
}
In [ ]:
Node node = new Node("Kevin");
In [ ]:
node.next = new Node("Elizabeth");
In [ ]:
node.name
In [ ]:
node.next.name