public interface Animal {
void speak();
}
public class Dog implements Animal{
void speak (){
System.out.println("This is dog.")
}
}
public class Cat implements Animal{
void speak (){
System.out.println("This is cat.")
}
}
@Module
public class Module{
@Provides
@Named("Dog")
static Animal providesDog() {
return new Dog();
}
@Provides
@Named("Cat")
static Animal providesCat() {
return new Cat();
}
}
public class AnimalOrchestrator {
@Inject
Animal animal;
public void speak(String type) {
if(type.equals("dog")
(Dog) animal.speak();
else
(Cat) animal.speak();
}
}
Is such kind of typecasting possible where at runtime we determining which dog/cat object should animal object translate as?
Following are some other ways using which such a functionality is achieved.
public class AnimalOrchestrator {
@Inject
Dog dog;
@Inject
Cat cat;
public void speak(String type) {
if(type.equals("dog")
dog.speak();
else
cat.speak();
}
}
The above code has the disadvantage that we need to create objects of dog and cat both although only one of the above will be used.
Another way is the following:
public class AnimalOrchestrator {
Animal animal;
public void speak(String type) {
if(type.equals("dog"){
animal = new Dog();
animal.speak();
} else {
animal = new Cat();
animal.speak();
}
}
}
With this, We have to create this object using new operator that i wanted to avoid so as to leverage dependency injection.
Is the first solution even possible? If yes, Which among these is better?
New contributor
Muskan Kuchhal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.