Kuby Block

Blog about programming, tech, society and more.

Mess with polymorphism



Polymorphism is one of four main concepts of Object Oriented Programming (OOP). In common, a parent interface defines common methods, then will be specify by children class. So although they have the same type, but each specific entity will do a method with different ways.

How to implement:

  • overloading
  • overriding

We have some scenarios:

  • We have some method with the same name and parameters.
  • We define an interface IA, then define a class A to implement that interface.
  • We define an abtrast class A, then define a class B to extends class A.
  • We define a class A, then define a class B to extends class A.


interface Animal

public interface Animal {
    default String getTypeName(){
        return "animal";

class Dog

public class Dog implements Animal {
    public String getTypeName(){
        return "dog";

class PugDog

public class PugDog extends Dog {
    public String getTypeName(){
        return "pug dog";

class Cat

public class Cat implements Animal {
    public String getTypeName(){
        return "cat";

class Duck

public class Duck implements Animal {

And do something with these classes:

public class App {
    public static void main(String[] args) {
        Animal dog = new Dog();
        Animal pugDog = new PugDog();
        Animal cat = new Cat();
        Animal duck = new Duck();

        System.out.println(dog.getTypeName()); // dog
        System.out.println(pugDog.getTypeName()); // pug dog
        System.out.println(cat.getTypeName()); // cat
        System.out.println(duck.getTypeName()); // animal

With the same method and the same declare type, but different implement class, we will have different method be invoked.

Another interesting example

class Weapon

public abstract class Weapon {
    protected String name;
    protected int damage;

    protected Weapon(){
        name = "no name weapon";
        damage = 0;

    abstract void initialize();

    public void attack(){
        System.out.println("[" + name + "] attacked with " + damage + " damage.");

class Sword

public class Sword extends Weapon {

    void initialize() {
        name = "sword";
        damage = 50;

class ShortGun

public class ShortGun extends Weapon{
    void initialize() {
        name = "short gun";
        damage = 75;

And Playground

public class Playground {
    public static void main(String[] args) {
        Weapon sword = new Sword();
        Weapon shortGun = new ShortGun();

        sword.attack(); //  [sword] attacked with 50 damage.
        shortGun.attack(); // [short gun] attacked with 75 damage.

comments powered by Disqus