Search code examples
javadispatch

Run method based on input, without if-statement logic


I have one single method that takes in 2 parameters:

public void generate(int size, String animal){
      // output a picture of the "animal" on java.swing of size "size"
}

So the possibility of the animals are Monkey, Giraffe, Dog, Cat, and Mouse. However, the assignment specifies that I can only have 1 method, no if-statements / cases / ternary operators, no external classes. So in the method, I have to create all 5 of these animals:

public void generate(int size, String animal){
      // output picture of Monkey
      // output picture of Giraffe
      // output picture of Dog
      // output picture of Cat
      // output picture of Mouse
}

So in turn, I was thinking I have to only make part of the method run based on the inputs. Is there any way to do this? The professor's hint was to use "multiple dispatch", but if there is only 1 method, how is this possible?


Solution

  • public interface Animal {
       public void draw(int size);
    }
    
    public class Monkey implements Animal {
       public void draw(int size) {
          // ...
       }
    }
    

    etc.