Learning Outcome 15th January 2020
Introduction
I learned about Interface-based Polymorphism as I was working a task to abstract some conditionals in my TicTacToe PlayGame()
function.
What is Polymorphism?
Polymorphism is an object-oriented programming concept that refers to the ability of a variable, function or object to take on multiple forms. Read more about Polymorphism here
What is Interface?
An interface is a syntactical contract that an entity should conform to. In other words, an interface defines the syntax that any entity must adhere to. Read more about Interface here
My Tic Tac Toe game has 3 player types, A Human Player, An Unbeatable player(Minimax), and a Beatable player (Random Player). All three player are setup in their separate modules and a method(function) responsible for finding the best position on the game board for every state of the game.
A class or function can implement an interface to define the implementation of the properties as defined in that interface. So I created three separate Player modules for each player type and have them stick to the same contract as the interface.
Why Use Interface?
As I have learned, an interface defines the specification of entities and they can be implemented by classes or functions
You can create multiple implementations of a single interface Interface
A class can implement more than one interface at a time.
An interface can extend another interface
You can add more properties(methods or functions) in the implementing class, which is not in the interface contract being implemented, however you must also implement all the existing properties available within the implemented interface unless they are optional.
You can define optional properties on an interface using
?
and read-only properties by using thereadonly
keyword in the property name
Reference: