Lecture 6 - Object Orientation
Lecture 6 - Object Orientation
Paradigms
Lecture 6: Abstract Data Types and Object Orientation
• Then talk about the additional requirements for defining your own
types, which motivates the move to OO
Structuring Data
• We talked about predefined types, and you will also have seen in
other lectures mechanisms for defining new ones, for example: arrays
(homogenous aggregations); and, records (heterogenous
aggregations)
• But these are rather restrictive. Are there more flexible ways of
defining new types?
We could try something like this …
type Int_Stack = struct{
int P[100]; // the stack proper
int top; // first readable element
}
Int_Stack create_stack(){
Int_Stack s = new Int_Stack();
s.top = 0;
return s;
}
Int_Stack push(Int_Stack s, int k){
if (s.top == 100) error;
s.P[s.top] = k;
s.top = s.top + 1;
return s;
}
int top(Int_Stack s){
return s.P[s.top];
}
Int_Stack pop(Int_Stack s){
if (s.top == 0) error;
s.top = s.top - 1;
return s;
} …
BUT
abstype Int_Stack{
type Int_Stack = struct{
int P[100];
int n;
int top;
}
}
The Signature, or Interface, of our ADT
abstype Int_Stack{
type Int_Stack = struct{
int P[100];
int n;
int top;
}
signature
Int_Stack create_stack();
Int_Stack push(Int_Stack s, int k);
int top(Int_Stack s);
Int_Stack pop(Int_Stack s);
bool empty(Int_Stack s);
…
}
An implementation of the interface
abstype Int_Stack{
…
operations
Int_Stack create_stack(){
Int_Stack s = new Int_Stack();
s.n = 0;
s.top = 0;
return s;
}
Int_Stack push(Int_Stack s, int k){
if (s.n == 100) error;
s.n = s.n + 1;
s.P[s.top] = k;
s.top = s.top + 1;
return s;
} …
Representation independence
We could also implement Int_Stack as, for example, a linked list. Both
implementations would respect the same specification:
• create_stack creates an empty stack.
• push inserts an element into the stack.
• top returns the element at the top of the stack without modifying the
stack itself. The stack must not be empty.
• pop removes the top elements from the stack. The stack must not be
empty.
• empty is true if and only if the stack is empty.
• We seem to be heading towards the OO that you all know and love.
But we are not there yet. Consider this example:
abstype Counter{
type Counter = int;
signature
void reset(Counter x);
int get(Counter x);
void inc(Counter x);
operations
void reset(Counter x){
x = 0;
}
int get(Counter c){
return x;
}
…
}
Enhance requirements for defining our own
types
class Counter{
private int x;
public void reset(){
x = 0;
}
public int get(){
return x;
}
public void inc(){
x = x+1;
}
}
Creating a NewCounter from Counter in OO