December 22, 2024

Typing

 

Is it possible to reset the attributes of an initialised object to different types of objects?

The answer to this question is yes.

With some languages you have to not only declare any variables that you use, but you must also state what type they are i.e. booleans or numbers or strings etc.
In Java for example you might write

int count = 0;
boolean isTrue = false;
float balance = 100.0f;

However, in Smalltalk there is no typing. For example:
If you had an initialised Account object, with a balance of 100, the following would work:

anAccount balance: nil

balance would now reference nil instead of 100

The method that the balance: nil message invokes (the code that is being executed on receipt of the balance: nil message) does not check to see what kind of object the argument is. So in fact you could set any object from any class to the balance. Of course this can create problems later.

anAccount balance + 100

will throw an error because nil (the message answer returned after the receipt of the balance message) does not understand the message
+ 100
Some methods are coded differently and they will check to make sure that the argument is of a suitable class.

The hover:by: message selector is another one that can cause havoc.
This message should take the form

aHoverFrog hover: Down by: 2

Or

aHoverFrog hover: Up by: 1

However you could equally write

aHoverFrog hover: Green by: 4

which is complete nonsense, but will not create an error. The reason is that the code of the hover:by: method checks to see whether or not the first argument is Down. If it's not, it will increase the value of height by the second argument provided that it does not make the height greater than 6.
But as long as the first argument is an object that Smalltalk "knows", and it certainly has a reference to the global variable Green, and as long as the height does not exceed 6, the height of the HoverFrog instance will be changed accordingly.

« Back to FAQ page

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Up to top of page