Sorry for the bad title, can’t come up with a concise way to put this.
I am thinking of having a list of objects that will have a specific interface. Each of these objects can then implement additional interfaces, but there is no guarantee which object will implement it. However, in one loop, I want to be able to call methods of any of their additional subtypes.
That is, 3 interfaces:
public interface IAnimal { ... }
public interface IEggLayer { public Egg layEgg(); }
public interface IMammal { public void sweat(); }
it will then be saved as
private List<IAnimal> animals= new ArrayList<IAnimal>();
therefore, instances added to the list can also be of type IEggLayeror IMammal, which have completely unrelated methods.
My initial instinct would then be to do
for(IAnimal animal : animals) {
if(animal instanceof IEggLayer) {
egg = ((IEggLayer)animal).layEgg();
}
if(animal instance of IMammal) {
((IMammal)animal).sweat();
}
}
But I was always told that type checking is a sign that the code really needs to be reorganized.
[, ], , doFunction() , , ?
, ?
...
[ , - Java-]
lvalue EggLayer, ,