at:tutorial:objects
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionNext revisionBoth sides next revision | ||
at:tutorial:objects [2007/07/10 22:04] – expanded tvcutsem | at:tutorial:objects [2007/07/19 07:59] – * tvcutsem | ||
---|---|---|---|
Line 94: | Line 94: | ||
def z := 0; | def z := 0; | ||
def sumOfSquares() { | def sumOfSquares() { | ||
- | super^sumOfSquares() + z*z | + | super^sumOfSquares() + z*z; |
}; | }; | ||
} | } | ||
Line 152: | Line 152: | ||
</ | </ | ||
- | ===== First-class | + | ===== First-class |
- | AmbientTalk provides a special message-sending operator '' | + | |
+ | AmbientTalk provides a special message-sending operator '' | ||
+ | |||
+ | < | ||
+ | def Enumerable := object: { | ||
+ | def collect: closure { | ||
+ | def c := self.new([]); | ||
+ | self.each: { |v| | ||
+ | c.add(closure(v)); | ||
+ | }; | ||
+ | c; | ||
+ | }; | ||
+ | }; | ||
+ | def Array := object: { | ||
+ | def elements := []; | ||
+ | def init(a) { elements := a; }; | ||
+ | def add(v) { elements := elements + [v]; self }; | ||
+ | def collect: closure { | ||
+ | Enumerable^collect: | ||
+ | }; | ||
+ | def each: clo { | ||
+ | 1.to: elements.length + 1 do: { |i| | ||
+ | clo(elements[i]); | ||
+ | }; | ||
+ | }; | ||
+ | }; | ||
+ | </ | ||
+ | |||
+ | A message sent to an object using the '' | ||
+ | |||
+ | < | ||
+ | > Array.add(1).add(2).add(3) | ||
+ | >> < | ||
+ | > def c := Array.collect: | ||
+ | >> < | ||
+ | > c.each: { |v| system.print(v)} | ||
+ | 234 | ||
+ | >> | ||
+ | </ | ||
+ | |||
+ | Of course, the example above is a bit contrived: we could have just assigned | ||
+ | |||
+ | Having described the semantics of '' | ||
< | < | ||
- | def point3D | + | def Point3D |
def z := 0; | def z := 0; | ||
def init(aX, aY, aZ) { | def init(aX, aY, aZ) { | ||
Line 162: | Line 204: | ||
z := aZ; | z := aZ; | ||
}; | }; | ||
- | } | + | }; |
</ | </ | ||
- | |||
- | A message sent to an object using the '' | ||
<note warning> | <note warning> | ||
- | The delegation operator | + | AmbientTalk, |
+ | |||
+ | Keep in mind, however, that '' | ||
</ | </ | ||
===== Encapsulation ===== | ===== Encapsulation ===== | ||
- | In AmbientTalk, all fields and methods are " | + | |
+ | AmbientTalk | ||
< | < | ||
- | > def makeObject(hidden) { | + | def makeBankAccount(balance) { |
- | object: { | + | object: { |
- | def foo() { /* use hidden */ } | + | def deposit(amnt) { |
- | } | + | balance := balance + amnt; |
+ | " | ||
+ | }; | ||
} | } | ||
+ | } | ||
</ | </ | ||
- | Due to the encapsulation of this object the following | + | Because |
< | < | ||
- | > makeObject(5).hidden; | + | > makeBankAccount(100).balance; |
- | >> | + | >> |
< | < | ||
</ | </ |
at/tutorial/objects.txt · Last modified: 2013/05/17 20:23 by tvcutsem