Search code examples
javainterfacedowncast

Pass an implementation of an object without casting


I apologize ahead of time for the title.

I am trying to pass an object Cat that implements Animal to an interface called Groom. In my Groom that handles grooming of Cat implementation, I have to downcast my object to understand what I am grooming, because the Groom interface accepts Animal as the parameter.

public interface Groom {
    void groom(Animal animal);
}

public class CatGroomer implements Groom {
    void groom(Animal animal) {
        Cat cat = (Cat) animal; // <---- how can i avoid this downcast
    }
}

public interface Animal {
    void do();
    void animal();
    void things();
}

public class Cat implements Animal {
    ...
}

Solution

  • Groom could be made generic like this:

    interface Groom<T extends Animal> {
      void groom(T t);
    }
    
    public class CatGroomer implements Groom<Cat> {
      void groom(Cat animal) {
    
      }
    }