Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Interfaces are used a lot because they are basically a blueprint of what your class should be able to do.</p> <p>For example, if you are writing a video game with characters, you can have an interface that holds all the methods that a character should have.</p> <p>For example</p> <pre><code>public interface Character { public void doAction(); } </code></pre> <p>And you have 2 characters, for example an ally and an enemy.</p> <pre><code>public class Ally implements Character { public void doAction() { System.out.println("Defend"); } } public class Enemy implements Character { public void doAction() { System.out.println("Attack"); } } </code></pre> <p>As you can see, both classes implement the interface, but they have different actions. Now you can create a character which implements your interface and have it perform its action. Depending on if it's an enemy or an ally, it'll perform a different action.</p> <pre><code>public Character ally = new Ally(); public Character enemy = new Enemy(); </code></pre> <p>And in your main program, you can create a method that accepts any object that implements your interface and have it perform it's action without knowing what kind of character it is.</p> <pre><code>void characterDoAction(Character char) { char.doAction(); } </code></pre> <p>If you would give ally to this method, the output would be:</p> <pre><code>Defend </code></pre> <p>If you would give enemy to this method, the output would be:</p> <pre><code>Attack </code></pre> <p>I hope this was a good enough example to help you understand the benefits of using interfaces.</p>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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