ST 4U 321: Using Polymorphism
Today's Smalltalk 4 You looks at the standard development process using VA Smalltalk and ENVY. If you have trouble viewing it here in the browser, you can also navigate directly to YouTube. To watch now, click on the image below:
If you have trouble viewing that directly, you can click here to download the video directly. If you need the video in a Windows Media format, then download that here.
You can also watch it on YouTube:
We've gone over a sketch of a Case Statement object in Smalltalk, but most of the time, polymorphism is the better answer. Today we'll give a simple example. Consider three classes that hold financial data:
Object subclass: #Instrument classInstanceVariableNames: '' instanceVariableNames: 'value ' classVariableNames: '' poolDictionaries: '' Object subclass: #SavingsAccount classInstanceVariableNames: '' instanceVariableNames: 'balance ' classVariableNames: '' poolDictionaries: '' Object subclass: #StockAccount classInstanceVariableNames: '' instanceVariableNames: 'stocks ' classVariableNames: '' poolDictionaries: ''
Each object calculates their value differently, but the idea is, we can send #currentValue to each, without needing to know the way they function internally (for an example in the base libraries, consider all of the objects that respond to #next). Here's the three implementations of #currentValue:
Instrument currentValue ^self value SavingsAccount currentValue ^self balance StockAccount currentValue ^self stocks inject: 0 into: [:subTotal :next | subTotal + next currentValue].
The nice part comes in when we need to get the values. We need not worry what kind of instrument we have; we simply send #currentValue to it:
| savings investment1 investment2 investment3 investment4 stockAcct | savings := SavingsAccount new: 1000. investment1 := Instrument value: 200. investment2 := Instrument value: 400. investment3 := Instrument value: 600. investment4 := Instrument value: 800. stockAcct := StockAccount stocks: (Array with: investment1 with: investment2 with: investment3 with: investment4). Transcript show: 'Savings: ', savings currentValue printString; cr. Transcript show: 'Stocks: ', stockAcct currentValue printString; cr. Transcript show: 'Investment 1: ', investment1 currentValue printString; cr.
Need more help? There's a screencast for other topics like this which you may want to watch. Questions? Try the "Chat with James" Google gadget over in the sidebar.
Tags: smalltalk, polymorphism
Enclosures:
[st4u321-iPhone.m4v ( Size: 3971079 )]