0

I need a object who refers to two diffenrent interfaces like this:

interface InterfaceA {
    public void a();
}

interface InterfaceB {
    public void b();
}

class Test() {
    Object <? implements InterfaceA, InterfaceB>; object;

    Test() {
        object.a();
        object.b();
    }
}

I know for inheritance there is this way: Class <? extends Main> a and a solution could be a helper class: class Helperclass implements InterfaceA, InterfaceB{}

Thanks for help and reading :)

Nero
  • 33
  • 8
  • Possible duplicate of [Return intersection of generic types](https://stackoverflow.com/questions/37835850/return-intersection-of-generic-types) – C-Otto Jan 24 '18 at 12:32
  • Possible duplicate of [Java Generics Wildcarding With Multiple Classes](https://stackoverflow.com/questions/745756/java-generics-wildcarding-with-multiple-classes) – Murat Karagöz Jan 24 '18 at 12:35

1 Answers1

5

If you add a generic type parameter to your Test class, you can require that this type parameter implement both interfaces:

class Test<T extends InterfaceA & InterfaceB> {
    T object;

    Test() {
        object.a();
        object.b();
    }

}

Of course you should initialize the object variable before calling methods.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thank you. What should I do, If I need two or more generics? – Nero Jan 24 '18 at 15:54
  • @Nero If you mean two or more generic type parameters, you can define as many as you need. For example: `class Test` – Eran Jan 24 '18 at 15:55