Interfaces

Interface

  • Objects define their interaction through their public methods
  • Interfaces:
    • allow us to implement abstraction
    • primarily define methods that other classes must implement
    • allows us to be more formal about the behavior classes promise to provide.
    • form a contract between the class and the outside interactions (this contract is enforced by the compiler)

Example

On Eclipse choose New > Interface

public interface CardGame {
    
    void setHand(int cardCount);
    
    int getHand();
    
    void setPlayers(int playerCount);
    
    int getPlayers();
    
}

Base on these methods, create a PokerGame class that implements CardGame

Solution

public class PokerGame implements CardGame {
    
    private int cardCount = 5;
    private int playerCount;
    
    public void setHand(int cardCount) {
        this.cardCount = cardCount;
    }
    
    public int getHand() {
        return cardCount;
    }
    
    public void setPlayers(int playerCount) {
        this.playerCount = playerCount;
    }
    
    public int getPlayers() {
        return playerCount;
    }
    

}

Build a better interface

In your groups, discuss how to write a better interface for a card game.

Think about different card games you know. What do they all have in common?

What is specific to a Poker Game?