2

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?

3
  • 1
    where does the in.next() came from? You might use a switch instead of if-else of -else` Commented Jan 2, 2013 at 17:20
  • It's a lot simpler than you're making it out to be: 1) An "interface" is implemented by a concrete class. 2) the concrete class is initialized by its constructor. As easy as that! :) Commented Jan 2, 2013 at 17:21
  • You can simply use the reference and object of the same class or direct-type. Dog d = new Dog(); Commented Jan 2, 2013 at 17:22

5 Answers 5

4

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
}
Sign up to request clarification or add additional context in comments.

Comments

3

There is nothing wrong in your way of doing. You can also look in to Factory design pattern.

Comments

1
    switch (x){
      case 1: 
       animal = new Dog();
       break;
      case 2:
       animal = new Cat();
       break;
      default
       animal = new Cow();
    }

Are you sure that Cow is a useful default?

Comments

1

Assuming they have a common super class Animal, it could have a static builder method that takes an int, you could do this

IAnimal animal = Animal.build(x);

where

public class Animal{
public static IAnimal build(int x){

 if(x==1) return new Dog();
 else if(x==2) return new Cat();

 return new Cow();
}}

1 Comment

Is that a design pattern reference? I mean, I agree. I would like to do something like this. What would that build method look like? I'm assuming this would turn IAnaimal into an abstract class then?
0

I would prefer a animal array

IAnimal animal = null;

IAnimal [] animals ={null,new Dog(),new Cat(),new Cow()};

animal = animals[x]

1 Comment

I don't like that approach. You are instantiating 3 objects, when you only need one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.