"Capture the instance vaguely" Instances can be assigned to variables of parent class type if the is-a relationship is established by inheritance.
SuperHero h = new SuperHero();
Regular SuperHero instance
Character c = new SuperHero();
Premise that the parent class of the SuperHero class has Character
public class Main {
public static void main(String[] args) {
Wizard w = new Wizard();
Character c = w; //Put in a Character type box
Matango m = new Matango();
c.name = "Wizard";
c.attack(m); //Can be called
c.fireball(m); //Get an 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 ())
-The reason why fireball () could not be called is that another character does not have fireball () (because it does not necessarily have it), so an error occurs.
・ I can say for sure that the box contains only one type of character
Character c = new Wizard();
Wizard w = c; //Get an error
Because the program is interpreted and translated line by line, c on the second line cannot be determined as Wizard.
Character c = new Wizard();
Wizard w = (Wizard)c; //Instruct forced type conversion
** The Slime (child) class inherits the Monster (parent) class ** Monster System.out.println ("Monster escaped."); 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
The slime escaped as a result of s.run ()
The slime escaped as a result of m.run ()
The actual result depends on the type of contents (Slime ()), the type of box (Monster m) is not related to the result
Character c = new Wizard();
Hero h = (Hero)c;
Compiles successfully, but fails when running Because it is a "lie composition"
if(c instanceof Wizard) { //If the contents of c can be regarded as Wizard
Wizard w = (Wizard)c; //Think of it as a Wizard
w.fly();
}
Recommended Posts