1

For training purposes I am creating Java project that will hold information about animals. There is an abstract class Animals which other will extend.

I would like to create carnivorous interface that in general will take any animal as an argument:

 public interface Carnivorous { public void eatAnimal(Animal animal); //alternative way I have tried public <T extends Animal> void eatAnimal2( T animal); } 

Problem is that in specific implementation I would like to narrow it down to specific classes that extends Animal:

public class Cat extends Animal implements Carnivorous { public Cat(String name, int expierence, String meow) { super(name, expierence); this.meow = meow; } public String getMeow() { return meow; } public void setMeow(String meow) { this.meow = meow; } @Override public String toString() { return "Cat [meow=" + meow + ", name=" + name + ", expierence=" + expierence + "]"; } @Override public void eatAnimal(Animal animal) { // TODO Auto-generated method stub } @Override public <T extends Animal> void eatAnimal2(T animal) { // TODO Auto-generated method stub } 

In this case I want the cat only to eat a mouse. I don't it to be able to eat let's say a zebra.

2 Answers 2

2

You can use generics in interfaces to help type-checking.

public static class Animal { public Animal() { } } public static class Rodent extends Animal { public Rodent() { } } public interface Carnivorous<A extends Animal> { public void eatAnimal(A animal); } public class Cat extends Animal implements Carnivorous<Rodent> { @Override public void eatAnimal(Rodent r) { } } 

Here I have a Carnovorous Cat that eats only Rodents.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I had a similar answer in mind but then I asked myself what to do if a cat eats rodents OR mice OR something else with no common super type else than Animal. Or-logic cannot easily be expressed by generics.
1

You can provide an interface what Carnivorous can eat.

public interface Carnivorous { public void eatAnimal(Animal animal); //alternative way I have tried public <T extends Animal> void eatAnimal2( T animal); Set<Class<? extends Animal>> canEat(); } 

And implementation, andt then check if Carnivorous can eat provided animal.

public Set<Class<? extends Animal>> canEat() { //TODO can be moved out of method Set<Class<? extends Animal>> classes = new HashSet<Class<? extends Animal>>(); classes.add(Mouse.class); return classes; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.