UML class diagram: characters of a game

UML class diagram: Characters of a game


public abstract class Character {       // superclass
    public abstract void show();        // has to be implemented by subclasses
}

public class Knight extends Character{
    public void show() {
        System.out.println("I am a noble knight.");
    }
}

extends Character{
    public void show() {
        System.out.println("I'm a nasty barbarian.");
    }
}

public class Witch extends Character{
    public void show() {
        System.out.println("I'm a beautiful witch.");
    }
}

import java.util.ArrayList;
import java.util.Random;

public class Game {

    static private ArrayList<Character> characters  = new ArrayList<>();  // Array of superclass type

    public static void main(String[] args) {
        initialize();
        play();
    }

    static private void initialize() {

        Random rand = new Random();
        int numCharacters = rand.nextInt(5) + 1;    // 1 <= number of characters <= 5

        for(int i=0; i<numCharacters; i++) {
            switch (rand.nextInt(3)) {              // late binding
                case 0:
                    characters.add(new Knight());
                    break;
                case 1:
                    characters.add(new Barbarian());
                    break;
                case 2:
                    characters.add(new Witch());
                    break;
            }
        }
    }
    static private void play() {
        for(Character character: characters) {          // "Form" of objects is decided at runtime
            character.show();                           // => POLYMORPHISM
        }
    }
}



Last modified: Saturday, 17 August 2019, 2:02 PM