Created
January 19, 2014 03:04
-
-
Save rajeevprasanna/8499990 to your computer and use it in GitHub Desktop.
Polymorphism example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package inheritanceIsaAndHasA.polymorphism; | |
public class GameShape { | |
public void displayShape() { | |
System.out.println("displaying shape"); | |
} | |
// more code | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package inheritanceIsaAndHasA.polymorphism; | |
public class PlayerPiece extends GameShape { | |
public void movePiece() { | |
System.out.println("moving game piece"); | |
} | |
// more code | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package inheritanceIsaAndHasA.polymorphism; | |
public class TestShapes { | |
public static void main(String[] args) { | |
PlayerPiece player = new PlayerPiece(); | |
TilePiece tile = new TilePiece(); | |
// The beautiful thing about polymorphism ("many forms") is that you can | |
// treat any subclass of GameShape as a GameShape | |
// If you add any extra method in the sub class, then u will not get | |
// those methods unless u typecast to that particular class. | |
//That means you can't use a GameShape variable to call, say, the getAdjacent() | |
// method even if the object passed in is of type TilePiece. | |
doShapes(player); | |
doShapes(tile); | |
} | |
// The doShapes() method knows only that the objects are | |
// a type of GameShape, since that's how the parameter is declared | |
public static void doShapes(GameShape shape) { | |
shape.displayShape(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package inheritanceIsaAndHasA.polymorphism; | |
public class TilePiece extends GameShape { | |
public void getAdjacent() { | |
System.out.println("getting adjacent tiles"); | |
} | |
// more code | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment