[Java] java (merit of polymorphism)

1 minute read

Combination of polymorphism and array

Code that does not combine arrays

public class Main {
  public static void main(String[] args) {
    Hero h1 = new Hero();
    Hero h2 = new Hero();
    Thief t1 = new Thief();
    Wizard w1 = new Wizard();
    Wizard w2 = new Wizard();
    // Start adventure!
    // First, stay at an inn
    h1.hp += 50;
    h2.hp += 50;
    t1.hp += 50;
    w1.hp += 50;
    w2.hp += 50;
  }
}

Code that combines arrays

public class Main {
  public static void main(String[] args) {
    Character[] c = new Character[5];
    c[0] = new Hero();
    c[1] = new Hero();
    c[2] = new Thief();
    c[3] = new Wizard();
    c[4] = new Wizard();
    // stay in an inn
    for (Character ch :c) {//take out one by one
      ch.hp += 50; //Recover 50 HP
    }
  }
}

Combination with argument

public class Hero extends Character{
  public void attack(Monster m) {/ attack all monsters
    System.out.println(this.name + "attack of!");
    System.out.println("10 points of damage to enemies");
    m.hp -= 10;
  }
}

Attack all if you inherit the monster class

Do different actions with the same instructions

public class Main {
  public static void main(String[] args) {
    Monster[] monsters = new Monster[3];
    monsters[0] = new Slime();
    monsters[1] = new Goblin();
    monsters[2] = new DeathBat();
    for (Monster m :monsters) {
      m.run(); // repeat the same instructions
    }
  }
}

Execution result Slime escaped Goblin escaped Hell bat escaped

Caller Escape Escape Escape Called side Slime ran away Goblin ran away Hell bat ran away