Search code examples
javainheritanceinterfacemultiple-inheritance

Interface inheritence in Java


In:

// services
public interface Mother { public Collection<? extends Father> getMamaStuff() {}} 
public interface Daughter extends Mother {}

// data
public interface Father { public String getPapaStuff() }
public interface Son extends Father { public String playLoudMusic() }

why is this not allowed:

public class Clazz {

    Clazz(Daughter daughter) {//boilerplate}

    public Collection<Son> idk = doughter.getMamaStuff();
}
  1. Is it because there is no way to know which implementation of Father will Clazz get?
  2. What is the good way to work around this?
  3. Is instanceof good practice in this case?

It seems to me there is no way around type checking.


Solution

  • The reason it's not allowed:

    interface Feline { }
    interface Kitten extends Feline {}
    interface Tiger extends Feline {}
    
    ...
    
    Cage<? extends Feline> makeCage();
    
    // at this point, it's actually really important that 
    // the right kind of cage was created...
    makeCage().put(new Tiger());
    

    Parameterizing Mother may work in your situation:

    public interface Mother<T extends Father> { 
      public Collection<T> getMamaStuff(); {}
    }