Jason
Jason

Reputation: 13986

Correct way to manage inheritance

Current I have code like this:

public void processAnimal(Animal a){
    if (a instanceof Cat){
        processCat((Cat)a);
    } else if (a instanceof Dog){
        processDog((Dog)a);
    } else if (a instanceof Bird){
        processBird((Bird)a);
    }
}

public void processCat(Cat c){
    ...
}

public void processDog(Dog d){
    ...
}

public void processBird(Bird b){
    ...
}

Is there any way to get rid of the boilerplate if statements?


Update: I have a set of models that get processed differently in different locations. Imagine each one of these are pets. A petstore may want to have a cat interact with other cats, and dogs interact with other dogs, wheras a home may want to have dogs and cats in the same locations.

So each model won't know how to interact in the given situations.

Upvotes: 1

Views: 53

Answers (1)

Warlord
Warlord

Reputation: 2826

You can define the processAnimal method in each respective subclass of Animal and then call it through animal.processAnimal(). Depending on the exact class of animal object, the correct method will be invoked.

ArrayList<Animal> animals = new ArrayList<Animal>();
animals.add(new Dog());
animals.add(new Cat());
animals.add(new Bird());

for (Animal animal : animals) {
    animal.processAnimal();  // appropriate method for each object will be called
}

Upvotes: 3

Related Questions