February 8, 2019 at 2:40 am #16057
Going deeper into this object-oriented programming, I wondered what an interface is, and what its possible uses are, some simple explanation to understand.
Thank you.February 8, 2019 at 8:07 pm #16058
An Interface contains declarations of methods, the parameters, and the return type.
Any class that implements the Interface is required to implement **everything**
from the Interface, exactly like it was declared.
It is like a contract/agreement and you can trust that the specific methods
are implemented in the classes.February 8, 2019 at 8:34 pm #16059
The best example in monkey2 is IContainer interface.
Stack and lists for example implements IContainer and can therfore be used with eachin loops.
You can create you own container that implements icontainer and you’ll be able to use it with eachin loops.
An interface force you to respect what was planned in some way. And if you forget to implement a part of it, you’ll have a compile error.
Interfaces are usefull for generic type constrains too. (using the ‘where’ keyword)
https://www.codingame.com/playgrounds/2290/demystifying-c-generics/generics-constraintsFebruary 9, 2019 at 6:02 am #16060
Small example:Monkey12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758#Import "<std>"#Import "<mojo>"Function Main()New mojo.app.AppInstanceLocal console := New ConsoleLocal printer := New PrinterLocal message := New MessageHelloWorld( console )HelloWorld( printer )HelloWorld( message )End#RemInterface IOutput#EndInterface IOutputMethod PrintLn( text:String )End#RemFunction HelloWorldParameter 1: Takes any object (instance of a class)that implements IOutput#EndFunction HelloWorld( obj:IOutput )obj.PrintLn( "Hello World!" )End#Remclass Console#EndClass Console Implements IOutputMethod PrintLn( s:String )Print sEndEnd#Remclass Printer#EndClass Printer Implements IOutputMethod PrintLn( s:String )Print "Printing to printer... ~n~t"+sEndEnd#Remclass Message#EndClass Message Implements IOutputMethod PrintLn( s:String )std.requesters.Notify( "Message", s )EndEnd
You must be logged in to reply to this topic.