Docsity

OOP Language Support: Multiple Representations, Encapsulation, Subtyping, Inheritance, Study notes of Electrical and Electronics Engineering

Partial preview of the text

Download OOP Language Support: Multiple Representations, Encapsulation, Subtyping, Inheritance and more Study notes Electrical and Electronics Engineering in PDF only on Docsity!

Language Support for Object-oriented Programming

I Multiple representations of the same interface

I Encapsulation

I Subtyping

I Inhertance

I Open recursion (in a method, you can call other methods on

“self” (“this”).

Objects

Here’s an object that represents a counter. We use lexical scoping,

references, and records.

c = let x = ref 1 in { get = λ :Unit. !x, inc = λ :Unit. x := succ !x };

c : { get : Unit → Nat, inc : Unit → Unit }

c.inc unit;

unit : Unit

c.get unit;

2 : Nat

Subtyping

I Suppose we also have some objects with the following type:

ResetCounter = {get:Unit→ Nat, inc:Unit→ Unit, reset:Unit→ Unit}

I The subtype rule for record width allows an object of type

ResetCounter in a place that expects a Counter.

Counter = { get : Unit → Nat, inc : Unit → Unit }; inc3 = (λ c:Counter. c.inc unit; c.inc unit; c.inc unit);

newResetCounter = λinit:Unit. let x = ref init in { get = λ :Unit. !x, inc = λ :Unit. x := succ !x reset = λ :Unit. x := init };

rc = inc3 (newResetCounter unit);

rc : ResetCounter rc.get unit; 4 : Nat

Objects with Multiple Data Members

newResetCounter = λini:Unit. let r = { x = ref ini, init = ini } in { get = λ :Unit. !r.x, inc = λ :Unit. r.x := succ !r.x reset = λ :Unit. r.x := r.init };

rc = newResetCounter 0;

rc : ResetCounter

Simple Classes

ResetCounterRep = { x : Ref Nat, init : Nat}

resetCounterClass = λr:ResetCounterRep. let super = counterClass r in { get = super.get, inc = super.inc, reset = λ :Unit. r.x := r.init };

newResetCounter = λini:Nat. let r { x=ref ini, init = ini} in resetCounterClass r;

Mutually Recursive Methods via References

SetCounter = {get:Unit→ Nat, set:Nat→ Unit, inc:Unit→ Unit};

setCounterClass = λr:CounterRep. λself: Source SetCounter. { get = λ :Unit. !r.x, set = λi:Nat. r.x := i, inc = λ :Unit. (!self).set (succ (!r.x)) };

dummySetCounter = { get = λ :Unit. 0, set = λi:Nat. unit, inc = λ :Unit. unit };

newSetCounter = λ : Unit. let r = { x = ref 1 } in let cAux = ref dummySetCounter in (cAux := (setCounterClass r cAux); !cAux);

sc = newSetCounter unit; sc.inc unit; sc.get unit;

Why not Objects via Self-Application

I Why don’t we do the normal thing of passing the object as

the first parameter of each method?

I We would need recursive types for this:

Counter = { get : Counter → Nat, inc : Counter → Unit };

I We’ll study recursive types in a few weeks.