The Object Concept Object-Oriented Programming 236703 Spring 2015
Identity The Basics Of Objects It must be possible to determine whether two objects are the same. State Set of characteristics Behavior Set of operations??? Object = ID + State + Behavior 2
Where Do Objects Come From? The problem space: o Employee o Salary o Date The program space: o Linked list o File o String Dilbert
Some Object Examples The complex number e 3+2I Characteristics: Real part, Imaginary part,... Operations: add, multiply,... The list (13, hello, true) Characteristics: Elements, length,... Operations: Add, remove, print, iterate over, sort,... The vehicle My old GMC, license plate #313-430 Characteristics: Speed, position,... Operations: Move, stop, accelerate,... 4
Objects in C Static Locals C allows functions to possess some state information, hence we can create (very) degenerate objects in C: Behavior: of one sort only Identity: single object int counter(void) { static int n = 0; return ++n; This is a global variable with a limited access. It simulates the state of the function 5
Objects in C Modules More interesting behavior can be achieved by using files and separate compilation in C. Still, Behavior: several functions Identity: single object /* stack.h: interface file */ void push(int val); int pop(void); This is how C simulates a module /* stack.c: implementation file */ #include "stack.h" static int stack[100], sp; void push(int val) { stack[sp++] = val; int pop(void) { return stack[--sp]; 6
int main(int ac, char** av) { FILE *fin; for (++av; *av!= NULL; av++) { if ((fin = fopen(*av, r )) == NULL) continue; Objects in C ADT FILE* is as close as you can get to an object in C. Behavior: many functions Identity: the file pointer State: the file s contents, flags, status,... while (!feof(fin)) putc(fgetc(fin)); This is an Abstract Data Type 7
Identity the property of an object which distinguishes it from all other objects. Identity name An object may have several different names An object may exist without any particular name bound to it Identity state State may change while identity may not Identity is tightly related to lifetime The time span extending from the time an object is first created and consumes space until that space is reclaimed An object can continue to exist even if all references to it are lost Same location + different lifetime different identity 8
Objects may live Object s Lifetime As long as the program is alive E.g., global objects in C++ While a certain block is running E.g., C++ stack (automatic) objects From creation (instantiation) till destruction E.g., C++ heap objects From creation till (after) no longer needed E.g., objects in Java, C#, Smalltalk Garbage Collected languages 9
In many cases, it becomes necessary for a method of an object to explicitly reference the object identity: Namespace ambiguity resolution ::foo or this->foo? Return reference to self Pass self as argument Notation: Self Reference to Identity this in C++, Java, C# self in Smalltalk Current in Eiffel 10
Identity & Equality Two Kinds of Equality: Is this the same object? Names equal if designate same object. Are they in the same state? Names equal if designate objects of the same state. Address 0x1960 12 Foo Bar 0x196C 12 Memory Contents A matter of value vs. reference semantics 11
Identity & Assignment Two Kinds of Assignment: Identity Assignment Reference is duplicated. Only one identity is involved. After the assignment: Two names refer to the same object State Assignment Copy the state information. After the assignment: Two names refer to distinct objects Address 0x1960 12 Foo Bar 0x196C 12 Memory Contents 12
State of Mine Everything is an object every field is an object o Changing the field = changing the object? How can you change a field of all its fields are also object? A matter of language semantics o Value vs. reference A matter of program semantics o Who owns a referenced object
How deep to copy? Duplicating an Object 0-level (aka: pointer copying) 1-level (aka: shallow copying) 2-level... Deep copy Who determines the depth? Parent (duplicated object) Children (object fields) 14
class PList { public Point head; public PList tail; 1-Level Copy PList onelevelcopy() { PList res = new PList(); res.head = head; res.tail = tail; return res; 15
class PList { public Point head; public PList tail; 2-Level Copy onelevelcopy() {... PList twolevelcopy() { PList res = new PList(); res.head = new Point(head.x, head.y); if (tail!= null) res.tail = tail.onelevelcopy(); return res; 16
class PList { public Point head; public PList tail; Deep Copy PList deepcopy() { PList res = new PList(); PList to = res; for (PList from = this; from!= null; from = from.tail) { to.head = new Point(from.head.x, from.head.y); to = to.tail = (from.tail == null)? return res; null : new PList(); 17
Depth Determined By Children public class Point { public final int x, y; public Point(int a, int b) { x = a; y = b; public Point copy() { return this; public class PList { public Point head; public PList tail; public PList copy() { PList res = new PList(); res.head = head.copy(); if (tail!= null) res.tail = tail.copy(); return res; 18
Static Aspect of Objects Attributes: placeholders in which the state is stored Nicknames: Fields, Properties, Instance Variables, Data Members Kinds of attributes: Immutable or Mutable Structure: the set of all attributes State: the current value of all of the object attributes Attributes Structure firstname = John lastname = D oh! age = 42 State 19
Immutable Objects: structure comprises only immutable attributes Example: Integer in Smalltalk, String in Java Extremely useful in parallel programming Kinds of values Static Aspect of Objects Scalars: Integer, Real, Boolean,... Aggregates: Array, List, Tree,... Objects: Invoice, Reservation,... Kinds of state representations Value semantics Reference/pointer semantics 20
Dynamic Aspect of Objects Active Object: encompasses its own thread of control; may undergo spontaneous state changes. Example: Ada s tasks, Java Runnable Quite rare in sequential OOPLs. Passive Object: can change state only if operated by other objects. Operations: An object may be queried for its state or requested to change it using its methods. Requestor should not have direct access to attributes. State encapsulation is enforced in many OOPLs. 21
Dynamic Aspect of Objects Message Passing: the means of communication between a client and object. Client: send a message. a symbolic name (called selector in Smalltalk) optional arguments. Object: invoke a method, optionally return an answer. Methods + Messages are called member functions in C++. 22
Examples of Messages The object vehicle can receive messages such as: Move forward at a given speed Accelerate Decelerate Stop The object list can receive messages such as: Add an element X Remove an element Y Return the length of yourself Sort yourself according to a given criteria Concatenate yourself with another list object Print yourself 23
Different Objects, Same Message, Different Methods In Object Oriented Programming, the message rotate left n degrees could be implemented differently by different objects A messages is the abstraction of a function call Shape: Do nothing if n == 0. Otherwise Rotate left n degrees. Circle: Do nothing. Rectangle: Do nothing if n == 180, 360,... Otherwise shape rotate. Square: Do nothing if n == 90, 270,... Otherwise rectangle rotate. 24
Protocol and Behavior Behavior: the way an object acts and reacts internal state changes message sent to other objects returned value Protocol: the envelope of the behavior 25
Kinds of Operations Mutator (Setter): alters state Inspector (selector, Getter): a query on the object s state. Constructor: creates a new object and/or initializes its state. Destructor: frees object s space and/or does other clean-up operations. Revealer: exposes an internal part of an object for direct external manipulation. 26
Operations on a Date class Date { public: // Constructor Date(int day = -1, int month = -1, int year = -1); // Inspectors int day(void) const { return d; int month(void) const { return m; int year(void) const { return y; // Mutators int day(int day); int month(int month); int year(int year); // Destructor ~Date(void) { cout << "Sic transit gloria mundi"; private: int d; int m; int y; ; In C++, as in many* other OOPLs, most* objects are instances of a class oop 27
Mutators of the Date Class int Date::day(int day) { Note that the mutators are not pure; they int res = d; d = day; also serve an inspection purpose return res; int Date::month(int month) { int res = m; Such mixed mode programming is m = month; counter purity, but may be useful return res; int Date::year(int year) { int res = y; y = year; return res; 28
Constructor of the Date Class Date::Date(int day, int month, int year) : d(day), // Constructor header: m(month), // Initialize all data members y(year) { // Additional initialization steps // Error checking // Accounting for leap year //... 29
Operations in an Array Class class Array { public: // Constructor Array(int n_): n(n_), buff(new double[n]) { // Destructor ~Array(void) { delete[] data; // Inspectors int n(void) { return n; double at(int i) { return buff[i]; // Revealer double& elem(int i) { return buff[i]; private: int n; float *buff; ; Revealers can serve the purpose of both inspectors and mutators. 30