Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Initializing a subclass

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?

like image 208
stackoverflow Avatar asked Jun 11 '26 00:06

stackoverflow


1 Answers

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
}
like image 55
Peter Lawrey Avatar answered Jun 15 '26 22:06

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!