|
We have created our object but apart from accessing and setting its variables once its created it
does not really do much. Lets return to the simple example and add a very simple "Instance Method" called Bark.
Then we will ne able to make our dog bark, again by using the dot operator.
//***************************************************************************
//**** Ex 3 - Adding Instance Methods to our object ************************
//***************************************************************************
winMain = New Window(640,480);
// Lets make two Dog objects!
dog1 = New Dog("Fido",2);
dog2 = New Dog("Butch", 10);
dog1.Bark();
dog2.Bark();
While(TRUE);
//***************************************************************************
//**** Below is all the code for a user object - Dog ************************
//***************************************************************************
Function Dog ( dname , dage )
{
//*** This is our dog object. This function runs whenever we create a new dog object
//*** This is sometimes called the "constructor".
//*** Lets give the dog some properties set by the user when they create a dog
This.name = dname;
This.age = dage;
//*** Instance Methods - Tells Jamagic which function to call for "Bark"
This.Bark = Dog_Bark;
}
Function Dog_Bark()
{
//*** The Bark Instance Method
CurWindow.WriteLn(name + " : Woof, Woof!");
//*** Note how we can access the instance variable such as name directly.
}
//***************************************************************************
//**** End of Code for object - Dog ****************************************
//***************************************************************************
The instance method "Bark" is called again using the dot operator just like how we accessed the member variables. Note that the convention to call the function Dog_Bark,
is just that, a convention. You can call it anything legal you like. But if you call it [OBJECT NAME]_[METHOD NAME] this makes it far easier for yourself and others to read and understand.
Your object can have as many or as few instance methods as is needed to complete its task. Instance methods provide the
interface to your objects abilities. Planning and designing instance methods is very important. Note : For users
familiar with other programming languages, Jamagic does not support overloading directly but a method that can be used
in outlined in the Jamagic Wiki.
If you plan to release the object to the public you should document fully all instance methods (with any parameters they require).
» Next : 5. Accessor Methods
|