What is the use of polymorphism? Where and when to use it? Can anyone explain with example?
Emmanuel C8,758 Points
A good example that allowed me to realize the brilliance of polymorphism was when I wrote a chess game, I had a base class called Piece, which represented all the types of pieces in the game of chess, ie pawn, knight, etc. I also have child classes of Piece for each of the pieces, ie a Pawn class, a Knight class, etc...
The base class had non specific methods and attributes in it, like determining what team it was on, or wether that piece was still alive, or the position its in on the board. But where polymorphism really came into play was with the move method. In the base Piece class it was virtual, and simply returned true, as Move() returns a boolean based on weather it was able to move successfully. I'm not sure how familiar you are the game of chess but each of the pieces has its own way of moving. ie a pawn can only move forward 1 square unless it was at the starting line, and it can also move 1 square diagonal but only if and enemy piece was present there. However the bishop can only move diagonally but as many squares it want as long and there isnt a piece in the way, and the same for the Rook, except it can only move in straight lines. each subclass overridden the move method depending on how that piece can move in the actual game.
With polymorphism each different piece can share similar methods and attributes of a base class yet, still have the ability to have custom methods and attributes specific to the subclass needs. They can also all be considered the base class when needed. ie to determine how many pieces a player had, it just counted Piece objects that were still alive regardless if it was pawn or a bishop, they could still be considered Piece objects, but when it become time to move them, they called their own overridden move method that made them different from each piece.
I hope this makes sense, there is a lot of courses here that cover it as polymorphism is a key feature of object oriented programming. Good Luck
Tonnie FanadezUX Design Techdegree Graduate 22,780 Points
Count me as a friend from now on. Never seen a perfect Java Polymorphism explanation!!
I play chess on my PC on a daily basis and I can relate to move() method for the different pieces with different movements.
Thanks for sharing.