|
Accessor methods as mentioned earlier are a cleaner and safer method of setting and getting member variables within your object.
Not used as much in Jamagic due to the fact all Jamagic member variables are always public (can be changed directly). Accessor methods are
a very simple type of instance method.
Below is an example of how to change the 'Dog' objects age and name with accessor methods.
//***************************************************************************
//**** Ex 4 - Adding Accessor Methods to our object ************************
//***************************************************************************
winMain = New Window(640,480);
// Lets make a Dog object!
dog1 = New Dog("Fido",2);
CurWindow.WriteLn("Fido is " + dog1.GetAge());
//*** Its Fido's birthday, lets update his age!
dog1.SetAge(dog1.GetAge() + 1);
CurWindow.WriteLn("Fido is now " + dog1.GetAge());
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/Accessor Methods
This.SetName = Dog_SetName;
This.GetName = Dog_GetName;
This.SetAge = Dog_SetAge;
This.GetAge = Dog_GetAge;
}
Function Dog_SetName(strNewName){ This.name = strNewName; }
Function Dog_GetName() { Return This.name; }
Function Dog_SetAge(intNewAge) { This.age = intNewAge; }
Function Dog_GetAge() { Return This.age; }
//***************************************************************************
//**** End of Code for object - Dog ****************************************
//***************************************************************************
» Next : 6. Conclusion
|