Skip to content

Instantly share code, notes, and snippets.

@rajeevprasanna
Created January 19, 2014 03:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajeevprasanna/8499990 to your computer and use it in GitHub Desktop.
Save rajeevprasanna/8499990 to your computer and use it in GitHub Desktop.
Polymorphism example
package inheritanceIsaAndHasA.polymorphism;
public class GameShape {
public void displayShape() {
System.out.println("displaying shape");
}
// more code
}
package inheritanceIsaAndHasA.polymorphism;
public class PlayerPiece extends GameShape {
public void movePiece() {
System.out.println("moving game piece");
}
// more code
}
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();
}
}
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