Junior — Middle
Is it possible to implement a factory method for creating an interface object?
sobes.tech AI
Answer from AI
Yes, the factory method can be used to create objects of an interface. In Java and Android, an interface itself cannot be instantiated, but a factory method can return a concrete implementation of that interface.
For example, you have an interface Animal and several classes implementing it:
interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Woof");
}
}
class Cat implements Animal {
public void makeSound() {
System.out.println("Meow");
}
}
class AnimalFactory {
public static Animal createAnimal(String type) {
if (type.equals("dog")) {
return new Dog();
} else if (type.equals("cat")) {
return new Cat();
} else {
throw new IllegalArgumentException("Unknown animal type");
}
}
}
Thus, calling AnimalFactory.createAnimal("dog") returns an object that implements the Animal interface. This is a classic example of the factory method for an interface.