What is an interface? (POO)

About Monkey 2 Forums Monkey 2 Programming Help What is an interface? (POO)

This topic contains 4 replies, has 4 voices, and was last updated by  NoOdle 1 week ago.

Viewing 5 posts - 1 through 5 (of 5 total)

  • Author


  • #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.





    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.




    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)




    Small example:




    An interface allows you to add specific functionality to any class, avoiding deep/complex class hierarchies. You can store instances of any class that implement the same interface in a collection and invoke any of the interface methods.

    Sorry if that makes no sense, I’m not the best at explaining things. Here’s a quick untested example:

Viewing 5 posts - 1 through 5 (of 5 total)