
How do I call a method from another method within the same class
Wen,
Quote:
> I am new to smalltalk. How do I call a method from another method
> within the same class.
Good to have you in the community. To answer your question -- you use the
"self" keyword followed by the name of the method. For example, let's
assume you have a Person class and each instance of person has instance
variables to hold the person's name and age. Now let's pretend that you
want to be able to assign the name individually and the age individually.
The method to assign the name might be:
======================
name: aName
name := aName
======================
The method to assign the age might be:
=======================
age: anAge
age := anAge
========================
So assume you want to assign the name and age together. The following
method would do that:
==========================
name: aName age: anAge
self name: aName.
self age: anAge
=========================
Notice that this method reuses the previous methods to accomplish its work.
This example not only demonstrates how to call a method from another within
the same class, but it also demonstrates the principle of expressing atomic
code one time -- as opposed to rewritting the code in many different places.
For example, let's say you want to store the age in days, although it is
supplied in years. So this could be accomplished by only changing the
"age:" method maybe like this:
===========================
age: anAgeInYears
age := anAgeInYears * 365
===========================
Hope that helps!
Regards,
Randy