Methods or functions within a class
Monkey Forums/Monkey Programming/Methods or functions within a class
| ||
This is my second question here. I am still new to Monkey syntax. As I noticed some tutorials here use functions in place of methods within a class, how does a function differ from a method? Thanks in advance. |
| ||
Methods are callable on an instance of a class while functions are called on the class itself and don't require an instance (and equally can't access instance fields or methods). If you're familiar with Java or C# then functions are similar to static methods. In more general language terms they're class methods: http://en.wikipedia.org/wiki/Method_(computer_programming)#Class_methods. |
| ||
a method allow direct access of fields with in a class but only when accessing through an instance. a method also has direct access to globals and const inside and outside a class. a method can only exist inside a class. a function works the same way with in an class as outside the class and does not have direct access to fields of a class or a class instance. a function inside a class has direct access to globals and const with in the inclusive class and globals and const outside any class. example of a method Class Add Field a:Int Field b:Int Method New(n1:Int,n2:Int) a = n1 b = n2 End Method Method display:Void() Print (a + b) End Method End Class 'demonstrates example use of the Add class Function Main() 'creates a variable of type Add Local a:Add 'create an instance of the class Add a = New Add(3,5) 'display results a.display() End Function try the example it works. |
| ||
Thanks, muddy_shoes! Yes, I am familiar with both C# and Java. I'll keep in mind functions in Monkey are similar to static methods. Thanks, Jesse. Now I understand the purpose of using functions, both inside and outside of a class whereas methods are declared only inside of a class. |
| ||
Thanks for this discussion. I just want someone to clarify one thing for me please. Is having a function inside a class the same as having a class method(+) like in objective-c wherein I can use the class name only? Edit: Nevermind, I should have tested it before asking this question. For those who doesn't know, it is the same. You can access the functions inside the class by using its class name alone. |
| ||
@darky000: You can access them too by using an instance, but that makes the function look like a method, wich can hit you back when you revisit the code a year after, so accesing class functions using the class name is not only possible, but highly advisable in my honest opinion. Using a instance name to call a class function is just like a syntax-correct way to add confusion to an expression. |
| ||
There are cases where it feels more syntactically natural IMO, but in general I agree it's best to expose the fact that it's a function rather than a method. |