What is the appropriate way to initialize an implemented class of an interface (determined by some logic)
Example
IAnaimal is an interface
Cat -> IAnimal
Dog -> IAnimal
Cow -> IAnimal
int x = in.nextInt();
IAnimal animal = null;
if(x==1)
animal = new Dog();
else if(x==2)
animal = new Cat();
else
animal = new Cow();
animal.destroyManKind();
Is this the correct approach? Is there a 'more' professional way of doing this?
I would have a cleaner way of reading the name instead of 1, 2 and 3 but you can use a switch in this case.
int choice = in.nextInt();
switch(choice) {
case 1: animal = new Dog(); break;
case 2: animal = new Cat(); break;
default: animal = new Cow(); break;
}
or using a string switch
String choice = in.next();
switch(choice.toLowerCase()) {
case "dog": animal = new Dog(); break;
case "cat": animal = new Cat(); break;
case "cow": animal = new Cow(); break;
default: // error
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With