|
Primer : Polymorphism (Part 1) |
|
|
Object-oriented principles are supported by 3 foundations:
|
|
This primer briefly explains polymorphism and why it is a powerful way to simplify
programming.
|
|
In the programming world, in order to maximize productivity, programmers never like
to re-write code that does the same thing over and over again. They typically create
their own library of routines that do a certain task and re-use them whenever they
are needed. The reasons are obvious.
4 squared In case this statement has not been explained to you before, here it is.Four (4) is a number. More specifically, it is a particular type of number called an Integer (integers are whole numbers). In VisualWorks, integers are divided into SmallIntegers and LargeIntegers. So, in OO terms, four (4) is an object and SmallInteger is its class. Another way of saying that would be "4 is an instance of the SmallInteger class". It's like re-wording "A salmon is a fish" to "This salmon I caught is an instance of the Fish class".Here is the big money question : Where do we find the squared method in the Smalltalk class library? Let's suppose that the squared method belongs to the SmallInteger class. That's where Smalltalk will find the method. This would mean that you could only perform the squared method on small integers. Since "squared" means any number times itself, couldn't you "square" a number like 3.14? If the squared method only belongs to class SmallInteger, then the answer is NO. ‘But,’ somebody might say, ‘you should also be able to "square" a number like 3.14.’ In Smalltalk, the number 3.14 is an instance of the class Float. A Float (short for floating decimal) is not a whole number but represents a number whose decimal could appear anywhere (i.e., 0.12 or 12.3456). So one solution would be to add another squared method to the class Float. What's wrong with solving the problem this way? The reasons why this is not a good solution should be obvious: The word polymorphism is made up of 2 words. "Poly" meaning "many" and "morph" meaning "form". So polymorphism allows a method to take on "many forms" which makes it re-usable and therefore more flexible. |
|
SummaryLater on, you will realize that in Smalltalk, you have access to the entire library of methods. It is possible to write your own methods and associate them to any class that you want. The idea is to write code "once and only once" and the only way to do that is to try and write code that could be used for as many objects as possible. |