-3

I am trying to build a simple API, where I have an interface AnimalService and its implementation classes are LionImpl, TigerImpl, ElephantImpl.
AnimalService has a method getHome().
And I have a properties file which contains the type of animal I'm using like,

animal=lion

So based on the animal type I am using, when I call my API (getHome() from AnimalService), the particular implementation class's getHome() method should be executed.

How can I achieve that?

Thanks in advance.

ktgirish
  • 257
  • 1
  • 2
  • 12

2 Answers2

3

You are describing how Java polymorphism works. Here is some code that corresponds to your description:

AnimalService.java

public interface AnimalService {
    String getHome();
}

ElephantImpl.java

public class ElephantImpl implements AnimalService {
    public String getHome() {
        return "Elephant home";
    }
}

LionImpl.java

public class LionImpl implements AnimalService {
    public String getHome() {
        return "Lion home";
    }
}

TigerImpl.java

public class TigerImpl implements AnimalService {
    public String getHome() {
        return "Tiger home";
    }
}

PolyFun.java

public class PolyFun {
    public static void main(String[] args) {
        AnimalService animalService = null;

        // there are many ways to do this:
        String animal = "lion";
        if (animal.compareToIgnoreCase("lion")==0)
            animalService = new LionImpl();
        else if (animal.compareToIgnoreCase("tiger")==0)
            animalService = new TigerImpl();
        else if (animal.compareToIgnoreCase("elephant")==0)
            animalService = new ElephantImpl();

        assert animalService != null;
        System.out.println("Home=" + animalService.getHome());
    }
}

For more information, see https://www.geeksforgeeks.org/dynamic-method-dispatch-runtime-polymorphism-java/

Mike Slinn
  • 7,705
  • 5
  • 51
  • 85
2

You can achieve this by creating a Factory class that houses an enum e.g.

public static AnimalServiceFactory(){

    public static AnimalService getInstance() { // you can choose to pass here the implmentation string or just do inside this class
        // read the properties file and get the implementation value e.g. lion
        final String result = // result from properties
        // get the implementation value from the enum
        return AnimalType.getImpl(result);
    }

    enum AnimalType {
        LION(new LionImpl()), TIGER(new TigerImpl()), etc, etc;

        AnimalService getImpl(String propertyValue) {
            // find the propertyValue and return the implementation
        }
    }
}

This is a high level code, not tested for syntax error etc.

johnII
  • 1,423
  • 1
  • 14
  • 20