Thursday, August 28, 2008

Answer to an interview problem !!! My Favourite Interview Question!!

there is one interview problem posted in
http://johnheintz.blogspot.com/2008/08/my-favorite-inverview-question.html, found in dzone.

Here is my version of solution:

I'll rather move deer under animal as well since it's an animal and implement Food as the interface for all those which are eatable like Deer,Grass,Cow etc.. so now my Animal class would be like

public abstract class Animal {
EatBehavior behavior;
public Animal(EatBehavior behavior) {
this.behavior = behavior;
}
public String eatFood(Food food) {
return behavior.eatFood(food);
}
}

Since eating is some kind of action or behavior i'll use an interface EatBehavior to denot that action

public interface EatBehavior {
public String eatFood(Food food);
public boolean isEatable(Food food);
}



Now finally i will have EatBehaviorImpl that does the eating and checking thing if it can be eatable or not??

public class EatBehaviorImpl implements EatBehavior {
public String eatFood(Food food) {
if (isEatable(food)) {
return "i can eat";
} else {
return "ek cannot eat";
}
}
public boolean isEatable(Food food) {
// return if food is eatable
return false;
}
}

i think isEatable make sense since we know in advance what can an animal eat or cannot pretty much so we can have some kind of map instead of relying on our models. So finally our any animal would be like

public class Tiger extends Animal {
public EatBehavior behavior;
public Tiger(EatBehavior behavior) {
super(behavior);
}
}
remember Tiger do not need to implement Food as it's on the top of the food chain, other animals or say grass object have to implement food.
now in any subclass of animal we just need to pass the specific impl of EatingBehavior. So I hope this makes sense, do suggest me if i am totally thinking out of this world.

No comments :