[Java] java (polymorphism)

1 minute read

Polymorphism

“Abruptly capturing an instance” If inheritance establishes an is-a relationship, you can assign an instance to a variable of parent class type

SuperHero h = new SuperHero();

Normal SuperHero instance

Character c = new SuperHero();

Assuming you have Character as the parent class of SuperHero class

Assigning an instance to an ambiguous type box

public class Main {
  public static void main(String[] args) {
    Wizard w = new Wizard();
    Character c = w; // put in Character type box
    Matango m = new Matango();
    c.name = "witch";
    c.attack(m); // can be called
    c.fireball(m); // error
  }
}

・Forget that the contents of the box (Character c) is Wizard ・Only attack() can be called because other characters have attack (Assuming that every character has attack()) ・Fireball() could not be called because other characters do not have fireball() (because they do not always have), an error occurs. ・The only thing that can be surely said is that the box contains only one character

How to call Wizard forcibly (downcast)

Character c = new Wizard();
Wizard w = c; // error

Because the program is interpreted and translated line by line, the second line c cannot be determined as Wizard.

Character c = new Wizard();
Wizard w = (Wizard)c; // Instruct forced type conversion

The process that moves when a method can be called

Monster (parent) class is inherited by Slime (child) class Monster System.out.println (“The monster ran away.”); Slime System.out.println (“Slime has escaped.”);

public class Main {
  public static void main(String[] args) {
    Slime s = new Slime();
    Monster m = new Slime();
    s.run();
    m.run();
  }
}

Execution result Slime escaped s.run() result Slime escaped Result of m.run() The actual result is determined by the content type (Slime()), the box type (Monster m) is irrelevant to the result

Downcast failure (ClassCastException)

Character c = new Wizard();
Hero h = (Hero)c;

Compiles successfully but gives an error when run Because it is a “lie composition”

Determine if you can cast safely (instanceof operator)

if(c instanceof Wizard) {/ // If the contents of c are considered Wizard
Wizard w = (Wizard)c; // Think of it as a Wizard
w.fly();
}

Tags:

Updated: