Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If I understood your question correctly it seems you have slightly misunderstood polymorphism, you don't need to know the type that implements the interface. </p> <p>See the following example, there is only one class that directly knows the types of each enemy, the initializing class.</p> <pre><code> import java.util.ArrayList; import java.util.List; public class SO18671999 { public static interface Enemy { public void Attack(Enemy other); public String getName(); } public static class Dragon implements Enemy { String name = "Onyxia"; public void Attack(Enemy other) { System.out.println(this.name + " attacks " + other.getName() + " for 10 dmg!"); } public String getName() { return this.name; } } public static class Cerberus implements Enemy { private String name; private int dmg; public Cerberus(String name, int dmg) { this.name = name; this.dmg = dmg; } @Override public void Attack(Enemy other) { System.out.println(this.name + " attacks " + other.getName() + " for " + this.dmg + " dmg!"); } @Override public String getName() { return this.name; } } public static class EnemyInitializer { private List&lt;Enemy&gt; enemies; public EnemyInitializer() { enemies = new ArrayList&lt;&gt;(); enemies.add(new Dragon()); enemies.add(new Cerberus("CerberusHeadLeft", 10)); enemies.add(new Cerberus("CerberusHeadRight", 10)); enemies.add(new Cerberus("CerberusHeadCenter", 20)); } public List&lt;Enemy&gt; getEnemies() { return enemies; } } public static class EnemyAttacker { private EnemyInitializer eI = new EnemyInitializer(); public void startAttacking() { List&lt;Enemy&gt; enemies = eI.getEnemies(); for (Enemy one : enemies) { for (Enemy two : enemies) { if (one == two) continue; one.Attack(two); } } } } public static void main(String[] args) { EnemyAttacker eAttacker = new EnemyAttacker(); eAttacker.startAttacking(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload