Polymorphism with generics?

51 Views Asked by At

I have a class A -> class B (child of A) -> class C (child of B) and class A -> class D. How can I write a function that return objects from class B and class D, example below. How to implement the calling part?

The problem is If I do A a = getFunction() I cannot access the B's functions.

public <T> T getFunction(IntegrationType integrationType) {
      return (T) integrationFactory.createIntegration(integrationType);
}
1

There are 1 best solutions below

0
Maksim Eliseev On

The problem is If I do A a = getFunction() I cannot access the B's functions.

You can use the instanceof operator. For example:

A a = getFunction();
if (a instanceof B) {
    B b = (B) a;
    // you can call the methods of B here
}

Or, if you are using Java 16 or higher, you can try the pattern matching as follows:

A a = getFunction();
if (a instanceof B b) {
    b.someMethod();
}