Search code examples
javagenericsinterface

How can I use interface with generics?


This is my structure.

public class FooInfo { ... }

public class FooAInfo extends FooInfo { ... }
public class FooBInfo extends FooInfo { ... }

public interface IFoo<T1 extends FooInfo> {
  void proc(T1 fooInfo);
}

public class FooA implements IFoo<FooAInfo> {
  void proc(FooAInfo fooInfo) { ... }
}
public class FooB implements IFoo<FooBInfo> {
  void proc(FooBInfo fooInfo) { ... }
}

And I want to use them like

public abstract class FooUser {
  protected IFoo<FooInfo> foo;
}

public class FooAUser extends FooUser {
  public FooAUser() {
    super.foo = new FooA();
  }
}

public class FooBUser extends FooUser {
  public FooBUser() {
    super.foo = new FooB();
  }
}

I want to initialize FooUser's foo variable in FooAUser and FooBUser child class.

But It doesn't work because new FooA() and new FooB() don't have <FooInfo>.

What should I do?


Solution

  • You just need to make FooUser generic:

    public abstract class FooUser<T extends FooInfo> {
      protected IFoo<T> foo;
    }
    
    public class FooAUser extends FooUser<FooAInfo> {
      public FooAUser() {
        super.foo = new FooA();
      }
    }
    
    public class FooBUser extends FooUser<FooBInfo> {
      public FooBUser() {
        super.foo = new FooB();
      }
    }
    

    Alternatively, you can use a generic wildcard (?) on your foo parameter:

    public abstract class FooUser {
      protected IFoo<?> foo;
    }
    
    public class FooAUser extends FooUser {
      public FooAUser() {
        super.foo = new FooA();
      }
    }
    
    public class FooBUser extends FooUser {
      public FooBUser() {
        super.foo = new FooB();
      }
    }
    

    (Unrelated to the question, but your proc() methods in your classes also need to be declared public.)