Implementing interfaces

An interface is a way of organising code, take the following example that may apply to a game scenario:

CharacterInterface.java

package basics;

public interface CharacterInterface {
    
    String getHit();
    int damage(int currentHealth, int damageAmount);
}

Then in the game we have characters;

James.java

package basics;

public class James implements CharacterInterface{

    // because we're implementing CharacterInterface, we have to implement
    // everything in the CharacterInterface
    @Override
    public String getHit() {
        
        String jamesGotHit = "James was hit!";
        return jamesGotHit;     
    }

    @Override
    public int damage(int currentHealth, int damageAmount) { 
        
        int newHealth= currentHealth-damageAmount;
        if (newHealth>0){
        return newHealth;
        } else {
            return 0;
        }
    } 
}

and
Emma.java

package basics;

public class Emma implements CharacterInterface{
    
    @Override
    public String getHit() {
        
        String jamesGotHit = "Emma was hit!";
        return jamesGotHit;     
    }

    @Override
    public int damage(int currentHealth, int damageAmount) { 
        
        int newHealth= currentHealth-damageAmount;
        if (newHealth>0){
        return newHealth;
        } else {
            return 0;
        }
    }
}

To run the program we have
StartingPoint.java

package basics;

public class StartingPoint {

    public static void main(String[] args) {
        // TODO code application logic here
        Emma emma1 = new Emma();
        
        System.out.println(emma1.getHit());
        System.out.println(emma1.damage(50, 2));
        
        James james1 = new James();
        
        System.out.println(james1.getHit());
        System.out.println(james1.damage(20, 4));
    }
}

Outputs:

Emma was hit!
48
James was hit!
16

I’m new to interfaces, the current thing that I can see why this is useful is that when we implement an interface, we have to use all the ‘methods’ within the interface. So when we set up James.java, or Emma.java, we have to override ALL the stuff within the interface – this will create consistency between the characters as they will all contain the same methods.

Leave a Reply