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/